jquery/test/runner/browserstack/api.js

333 lines
8.8 KiB
JavaScript
Raw Normal View History

Tests: migrate testing infrastructure to minimal dependencies This is a complete rework of our testing infrastructure. The main goal is to modernize and drop deprecated or undermaintained dependencies (specifically, grunt, karma, and testswarm). We've achieved that by limiting our dependency list to ones that are unlikely to drop support any time soon. The new dependency list includes: - `qunit` (our trusty unit testing library) - `selenium-webdriver` (for spinning up local browsers) - `express` (for starting a test server and adding middleware) - express middleware includes uses of `body-parser` and `raw-body` - `yargs` (for constructing a CLI with pretty help text) - BrowserStack (for running each of our QUnit modules separately in all of our supported browsers) - `browserstack-local` (for opening a local tunnel. This is the same package still currently used in the new Browserstack SDK) - We are not using any other BrowserStack library. The newest BrowserStack SDK does not fit our needs (and isn't open source). Existing libraries, such as `node-browserstack` or `browserstack-runner`, either do not quite fit our needs, are under-maintained and out-of-date, or are not robust enough to meet all of our requirements. We instead call the [BrowserStack REST API](https://github.com/browserstack/api) directly. **BrowserStack** - automatically retries individual modules in case of test failure(s) - automatically attempts to re-establish broken tunnels - automatically refreshes the page in case a test run has stalled - Browser workers are reused when running isolated modules in the same browser - runs all browsers concurrently and uses as many sessions as are available under the BrowserStack plan. It will wait for available sessions if there are none. - supports filtering the available list of browsers by browser name, browser version, device, OS, and OS version (see `npm run test:unit -- --list-browsers` for more info). It will retrieve the latest matching browser available if any of those parameters are not specified. Supports latest and latest-\d+ in place of browser version. - cleans up after itself (closes the local tunnel, stops the test server, etc.) - Requires `BROWSERSTACK_USERNAME` and `BROWSERSTACK_ACCESS_KEY` environment variables. **Selenium** - supports running any local browser as long as the driver is installed, including support for headless mode in Chrome, FF, and Edge - supports running `basic` tests on the latest [jsdom](https://github.com/jsdom/jsdom#readme), which can be seen in action in this PR (see `test:browserless`) - Node tests will run as before in PRs and all non-dependabot branches, but now includes tests on real Safari in a GH actions macos image instead of playwright-webkit. - can run multiple browsers and multiple modules concurrently Other notes: - Stale dependencies have been removed and all remaining dependencies have been upgraded with a few exceptions: - `sinon`: stopped supporting IE in version 10. But, `sinon` has been updated to 9.x. - `husky`: latest does not support Node 10 and runs on `npm install`. Needed for now until git builds are migrated to GitHub Actions. - `rollup`: latest does not support Node 10. Needed for now until git builds are migrated to GitHub Actions. - BrowserStack tests are set to run on each `main` branch commit - `debug` mode leaves Selenium browsers open whether they pass or fail and leaves browsers with test failures open on BrowserStack. The latter is to avoid leaving open too many sessions. - This PR includes a workflow to dispatch BrowserStack runs on-demand - The Node version used for most workflow tests has been upgraded to 20.x - updated supportjQuery to 3.7.1 Run `npm run test:unit -- --help` for CLI documentation Close gh-5427
2024-03-05 18:53:39 +00:00
/**
* Browserstack API is documented at
* https://github.com/browserstack/api
*/
import { createAuthHeader } from "./createAuthHeader.js";
const browserstackApi = "https://api.browserstack.com";
const apiVersion = 5;
const username = process.env.BROWSERSTACK_USERNAME;
const accessKey = process.env.BROWSERSTACK_ACCESS_KEY;
// iOS has null for version numbers,
// and we do not need a similar check for OS versions.
const rfinalVersion = /(?:^[0-9\.]+$)|(?:^null$)/;
const rlatest = /^latest-(\d+)$/;
const rnonDigits = /(?:[^\d\.]+)|(?:20\d{2})/g;
async function fetchAPI( path, options = {}, versioned = true ) {
if ( !username || !accessKey ) {
throw new Error(
"BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY environment variables must be set."
);
}
const init = {
method: "GET",
...options,
headers: {
authorization: createAuthHeader( username, accessKey ),
accept: "application/json",
"content-type": "application/json",
...options.headers
}
};
const response = await fetch(
`${ browserstackApi }/${ versioned ? `${ apiVersion }/` : "" }${ path }`,
init
);
if ( !response.ok ) {
console.log(
`\n${ init.method } ${ path }`,
response.status,
response.statusText
);
throw new Error( `Error fetching ${ path }` );
}
return response.json();
}
/**
* =============================
* Browsers API
* =============================
*/
function compareVersionNumbers( a, b ) {
if ( a != null && b == null ) {
return -1;
}
if ( a == null && b != null ) {
return 1;
}
if ( a == null && b == null ) {
return 0;
}
const aParts = a.replace( rnonDigits, "" ).split( "." );
const bParts = b.replace( rnonDigits, "" ).split( "." );
if ( aParts.length > bParts.length ) {
return -1;
}
if ( aParts.length < bParts.length ) {
return 1;
}
for ( let i = 0; i < aParts.length; i++ ) {
const aPart = Number( aParts[ i ] );
const bPart = Number( bParts[ i ] );
if ( aPart < bPart ) {
return -1;
}
if ( aPart > bPart ) {
return 1;
}
}
if ( rnonDigits.test( a ) && !rnonDigits.test( b ) ) {
return -1;
}
if ( !rnonDigits.test( a ) && rnonDigits.test( b ) ) {
return 1;
}
return 0;
}
function sortBrowsers( a, b ) {
if ( a.browser < b.browser ) {
return -1;
}
if ( a.browser > b.browser ) {
return 1;
}
const browserComparison = compareVersionNumbers(
a.browser_version,
b.browser_version
);
if ( browserComparison ) {
return browserComparison;
}
if ( a.os < b.os ) {
return -1;
}
if ( a.os > b.os ) {
return 1;
}
const osComparison = compareVersionNumbers( a.os_version, b.os_version );
if ( osComparison ) {
return osComparison;
}
const deviceComparison = compareVersionNumbers( a.device, b.device );
if ( deviceComparison ) {
return deviceComparison;
}
return 0;
}
export async function getBrowsers( { flat = false } = {} ) {
const query = new URLSearchParams();
if ( flat ) {
query.append( "flat", true );
}
const browsers = await fetchAPI( `/browsers?${ query }` );
return browsers.sort( sortBrowsers );
}
function matchVersion( browserVersion, version ) {
if ( !version ) {
return false;
}
const regex = new RegExp(
`^${ version.replace( /\\/g, "\\\\" ).replace( /\./g, "\\." ) }\\b`,
"i"
);
return regex.test( browserVersion );
}
export async function filterBrowsers( filter ) {
const browsers = await getBrowsers( { flat: true } );
if ( !filter ) {
return browsers;
}
const filterBrowser = ( filter.browser ?? "" ).toLowerCase();
const filterVersion = ( filter.browser_version ?? "" ).toLowerCase();
const filterOs = ( filter.os ?? "" ).toLowerCase();
const filterOsVersion = ( filter.os_version ?? "" ).toLowerCase();
const filterDevice = ( filter.device ?? "" ).toLowerCase();
const filteredWithoutVersion = browsers.filter( ( browser ) => {
return (
( !filterBrowser || filterBrowser === browser.browser.toLowerCase() ) &&
( !filterOs || filterOs === browser.os.toLowerCase() ) &&
( !filterOsVersion || matchVersion( browser.os_version, filterOsVersion ) ) &&
( !filterDevice || filterDevice === ( browser.device || "" ).toLowerCase() )
);
} );
if ( !filterVersion ) {
return filteredWithoutVersion;
}
if ( filterVersion.startsWith( "latest" ) ) {
const groupedByName = filteredWithoutVersion
.filter( ( b ) => rfinalVersion.test( b.browser_version ) )
.reduce( ( acc, browser ) => {
acc[ browser.browser ] = acc[ browser.browser ] ?? [];
acc[ browser.browser ].push( browser );
return acc;
}, Object.create( null ) );
const filtered = [];
for ( const group of Object.values( groupedByName ) ) {
const latest = group[ group.length - 1 ];
// Mobile devices do not have browser version.
// Skip the version check for these,
// but include the latest in the list if it made it
// through filtering.
if ( !latest.browser_version ) {
// Do not include in the list for latest-n.
if ( filterVersion === "latest" ) {
filtered.push( latest );
}
continue;
}
// Get the latest version and subtract the number from the filter,
// ignoring any patch versions, which may differ between major versions.
const num = rlatest.exec( filterVersion );
const version = parseInt( latest.browser_version ) - ( num ? num[ 1 ] : 0 );
const match = group.findLast( ( browser ) => {
return matchVersion( browser.browser_version, version.toString() );
} );
if ( match ) {
filtered.push( match );
}
}
return filtered;
}
return filteredWithoutVersion.filter( ( browser ) => {
return matchVersion( browser.browser_version, filterVersion );
} );
}
export async function listBrowsers( filter ) {
const browsers = await filterBrowsers( filter );
console.log( "Available browsers:" );
for ( const browser of browsers ) {
let message = ` ${ browser.browser }_`;
if ( browser.device ) {
message += `:${ browser.device }_`;
} else {
message += `${ browser.browser_version }_`;
}
message += `${ browser.os }_${ browser.os_version }`;
console.log( message );
}
}
export async function getLatestBrowser( filter ) {
if ( !filter.browser_version ) {
filter.browser_version = "latest";
}
const browsers = await filterBrowsers( filter );
return browsers[ browsers.length - 1 ];
}
/**
* =============================
* Workers API
* =============================
*/
/**
* A browser object may only have one of `browser` or `device` set;
* which property is set will depend on `os`.
*
* `options`: is an object with the following properties:
* `os`: The operating system.
* `os_version`: The operating system version.
* `browser`: The browser name.
* `browser_version`: The browser version.
* `device`: The device name.
* `url` (optional): Which URL to navigate to upon creation.
* `timeout` (optional): Maximum life of the worker (in seconds). Maximum value of `1800`. Specifying `0` will use the default of `300`.
* `name` (optional): Provide a name for the worker.
* `build` (optional): Group workers into a build.
* `project` (optional): Provide the project the worker belongs to.
* `resolution` (optional): Specify the screen resolution (e.g. "1024x768").
* `browserstack.local` (optional): Set to `true` to mark as local testing.
* `browserstack.video` (optional): Set to `false` to disable video recording.
* `browserstack.localIdentifier` (optional): ID of the local tunnel.
*/
export function createWorker( options ) {
return fetchAPI( "/worker", {
method: "POST",
body: JSON.stringify( options )
} );
}
/**
* Returns a worker object, if one exists, with the following properties:
* `id`: The worker id.
* `status`: A string representing the current status of the worker.
* Possible statuses: `"running"`, `"queue"`.
*/
export function getWorker( id ) {
return fetchAPI( `/worker/${ id }` );
}
export async function deleteWorker( id ) {
return fetchAPI( `/worker/${ id }`, { method: "DELETE" } );
}
export function getWorkers() {
return fetchAPI( "/workers" );
}
/**
* Stop all workers
*/
export async function stopWorkers() {
const workers = await getWorkers();
// Run each request on its own
// to avoid connect timeout errors.
console.log( `${ workers.length } workers running...` );
for ( const worker of workers ) {
try {
await deleteWorker( worker.id );
} catch ( error ) {
// Log the error, but continue trying to remove workers.
console.error( error );
}
}
console.log( "All workers stopped." );
}
/**
* =============================
* Plan API
* =============================
*/
export function getPlan() {
return fetchAPI( "/automate/plan.json", {}, false );
}
export async function getAvailableSessions() {
try {
const [ plan, workers ] = await Promise.all( [ getPlan(), getWorkers() ] );
return plan.parallel_sessions_max_allowed - workers.length;
} catch ( error ) {
console.error( error );
return 0;
}
}