orchestration | Cell 6 | screenshot all sessions | Search

The cleanUpSessions function manages and closes all active Selenium WebDriver sessions, cleans up session data, and restarts the Selenium server to ensure a clean environment for subsequent tests.

Run example

npm run import -- "clean up old selenium sessions"

clean up old selenium sessions

var path = require('path');
var fs = require('fs');
var importer = require('../Core');
var {
    getSeleniumServer,
    runSeleniumCell,
    execCmd
} = importer.import("selenium docker",
"set up selenium server",
"selenium cell",
"spawn child process");

var regexToArray = (ex, str, i = 0) => {
    var co = []; var m; while ((m = ex.exec(str)) && co.push(m[i])); return co;
};

var TOKEN_DIR = path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.credentials');
var SESSIONS_PATH = path.join(TOKEN_DIR, 'sessions.json');

function closeAllSessions(logs) {
    const sessLogs = regexToArray(/\/session\/(.+?)\//ig, logs.join('\n'), 1);
    const sessions = sessLogs.filter((s, i, arr) => arr.indexOf(s) === i)
}

function cleanUpSessions() {
    return getSeleniumServer()
        .then(log => closeAllSessions(log))
        .catch(e => {
            console.log(e);
            if(((e.data || e) + '').indexOf('docker: not found') === -1) {
                throw e;
            } else {
                // try to kill chrome
                return execCmd('sudo killall chrome');
            }
        })
        .then(() => {
            fs.writeFileSync(SESSIONS_PATH, '[]');
            return runSeleniumCell(false);
        })
}
module.exports = cleanUpSessions;

if(typeof $ !== 'undefined') {
    $.async()
    cleanUpSessions()
        .then(r => $.sendResult(r))
        .catch(e => $.sendError(e))
}

What the code could have been:

// Import necessary modules
const path = require('path');
const fs = require('fs');
const { getSeleniumServer, runSeleniumCell, execCmd } = require('../Core');

// Define constants
const TOKEN_DIR = path.join([
  process.env.HOME,
  process.env.HOMEPATH,
  process.env.USERPROFILE
].find(Boolean) || process.env.HOME, '.credentials');
const SESSIONS_PATH = path.join(TOKEN_DIR,'sessions.json');

// Define regular expression function to extract array from string
const regexToArray = (regex, str, index = 0) => {
  const matches = [];
  let match;
  while ((match = regex.exec(str)) && matches.push(match[index]));
  return matches;
};

// Define function to close all sessions
const closeAllSessions = (logs) => {
  const sessionLogs = regexToArray(/\/session\/(.+?)\//ig, logs.join('\n'), 1);
  return sessionLogs.filter((session, index, self) => self.indexOf(session) === index);
};

// Define function to clean up sessions
const cleanUpSessions = async () => {
  try {
    // Get Selenium server logs
    const log = await getSeleniumServer();
    // Close all sessions
    const closedSessions = closeAllSessions(log);
    // Remove duplicate sessions
    const uniqueSessions = closedSessions.filter((session, index, self) => self.indexOf(session) === index);
    // Write empty sessions list to file
    fs.writeFileSync(SESSIONS_PATH, '[]');
  } catch (error) {
    // Check if error is due to Docker not being found
    if ((error.data || error).indexOf('docker: not found') === -1) {
      // Re-throw error
      throw error;
    } else {
      // Try to kill Chrome process
      await execCmd('sudo killall chrome');
    }
  } finally {
    // Re-run Selenium cell
    await runSeleniumCell(false);
  }
};

// Export cleanUpSessions function
module.exports = cleanUpSessions;

// Check if $ is a global object and run cleanUpSessions
if (typeof $!== 'undefined') {
  $.async();
  cleanUpSessions()
 .then((result) => $.sendResult(result))
 .catch((error) => $.sendError(error));
}

This code defines a function cleanUpSessions that manages and closes all active Selenium WebDriver sessions, cleans up session data, and restarts the Selenium server.

Here's a breakdown:

  1. Imports:

  2. regexToArray Function:

  3. Paths:

  4. closeAllSessions Function:

  5. cleanUpSessions Function:

  6. Module Exports:

  7. Async Execution (if $ is defined):

In essence, this code provides a mechanism to clean up Selenium WebDriver sessions, remove session data, and restart the server, ensuring a clean slate for subsequent tests.