How to use parseOSReleaseText method in Playwright Internal

Best JavaScript code snippet using playwright-internal

utils.js

Source:utils.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.arrayToObject = arrayToObject;6exports.assert = assert;7exports.calculateSha1 = calculateSha1;8exports.canAccessFile = canAccessFile;9exports.constructURLBasedOnBaseURL = constructURLBasedOnBaseURL;10exports.createGuid = createGuid;11exports.debugAssert = debugAssert;12exports.debugMode = debugMode;13exports.download = download;14exports.existsAsync = void 0;15exports.fetchData = fetchData;16exports.getAsBooleanFromENV = getAsBooleanFromENV;17exports.getFromENV = getFromENV;18exports.getPlaywrightVersion = getPlaywrightVersion;19exports.getUserAgent = getUserAgent;20exports.headersArrayToObject = headersArrayToObject;21exports.headersObjectToArray = headersObjectToArray;22exports.hostPlatform = void 0;23exports.isError = isError;24exports.isFilePayload = isFilePayload;25exports.isObject = isObject;26exports.isRegExp = isRegExp;27exports.isString = isString;28exports.isUnderTest = isUnderTest;29exports.makeWaitForNextTask = makeWaitForNextTask;30exports.mkdirIfNeeded = mkdirIfNeeded;31exports.monotonicTime = monotonicTime;32exports.objectToArray = objectToArray;33exports.removeFolders = removeFolders;34exports.setUnderTest = setUnderTest;35exports.spawnAsync = spawnAsync;36exports.streamToString = streamToString;37exports.transformCommandsForRoot = transformCommandsForRoot;38exports.wrapInASCIIBox = wrapInASCIIBox;39var _path = _interopRequireDefault(require("path"));40var _fs = _interopRequireDefault(require("fs"));41var _rimraf = _interopRequireDefault(require("rimraf"));42var crypto = _interopRequireWildcard(require("crypto"));43var _os = _interopRequireDefault(require("os"));44var _http = _interopRequireDefault(require("http"));45var _https = _interopRequireDefault(require("https"));46var _child_process = require("child_process");47var _proxyFromEnv = require("proxy-from-env");48var URL = _interopRequireWildcard(require("url"));49var _ubuntuVersion = require("./ubuntuVersion");50var _progress = _interopRequireDefault(require("progress"));51function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }52function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }53function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }54/**55 * Copyright (c) Microsoft Corporation.56 *57 * Licensed under the Apache License, Version 2.0 (the "License");58 * you may not use this file except in compliance with the License.59 * You may obtain a copy of the License at60 *61 * http://www.apache.org/licenses/LICENSE-2.062 *63 * Unless required by applicable law or agreed to in writing, software64 * distributed under the License is distributed on an "AS IS" BASIS,65 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.66 * See the License for the specific language governing permissions and67 * limitations under the License.68 */69// `https-proxy-agent` v5 is written in TypeScript and exposes generated types.70// However, as of June 2020, its types are generated with tsconfig that enables71// `esModuleInterop` option.72//73// As a result, we can't depend on the package unless we enable the option74// for our codebase. Instead of doing this, we abuse "require" to import module75// without types.76const ProxyAgent = require('https-proxy-agent');77const existsAsync = path => new Promise(resolve => _fs.default.stat(path, err => resolve(!err)));78exports.existsAsync = existsAsync;79function httpRequest(params, onResponse, onError) {80 const parsedUrl = URL.parse(params.url);81 let options = { ...parsedUrl82 };83 options.method = params.method || 'GET';84 options.headers = params.headers;85 const proxyURL = (0, _proxyFromEnv.getProxyForUrl)(params.url);86 if (proxyURL) {87 if (params.url.startsWith('http:')) {88 const proxy = URL.parse(proxyURL);89 options = {90 path: parsedUrl.href,91 host: proxy.hostname,92 port: proxy.port93 };94 } else {95 const parsedProxyURL = URL.parse(proxyURL);96 parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:';97 options.agent = new ProxyAgent(parsedProxyURL);98 options.rejectUnauthorized = false;99 }100 }101 const requestCallback = res => {102 const statusCode = res.statusCode || 0;103 if (statusCode >= 300 && statusCode < 400 && res.headers.location) httpRequest({ ...params,104 url: res.headers.location105 }, onResponse, onError);else onResponse(res);106 };107 const request = options.protocol === 'https:' ? _https.default.request(options, requestCallback) : _http.default.request(options, requestCallback);108 request.on('error', onError);109 if (params.timeout !== undefined) {110 const rejectOnTimeout = () => {111 onError(new Error(`Request to ${params.url} timed out after ${params.timeout}ms`));112 request.abort();113 };114 if (params.timeout <= 0) {115 rejectOnTimeout();116 return;117 }118 request.setTimeout(params.timeout, rejectOnTimeout);119 }120 request.end(params.data);121}122function fetchData(params, onError) {123 return new Promise((resolve, reject) => {124 httpRequest(params, async response => {125 if (response.statusCode !== 200) {126 const error = onError ? await onError(params, response) : new Error(`fetch failed: server returned code ${response.statusCode}. URL: ${params.url}`);127 reject(error);128 return;129 }130 let body = '';131 response.on('data', chunk => body += chunk);132 response.on('error', error => reject(error));133 response.on('end', () => resolve(body));134 }, reject);135 });136}137function downloadFile(url, destinationPath, options = {}) {138 const {139 progressCallback,140 log = () => {}141 } = options;142 log(`running download:`);143 log(`-- from url: ${url}`);144 log(`-- to location: ${destinationPath}`);145 let fulfill = ({146 error147 }) => {};148 let downloadedBytes = 0;149 let totalBytes = 0;150 const promise = new Promise(x => {151 fulfill = x;152 });153 httpRequest({154 url,155 headers: options.userAgent ? {156 'User-Agent': options.userAgent157 } : undefined158 }, response => {159 log(`-- response status code: ${response.statusCode}`);160 if (response.statusCode !== 200) {161 const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`); // consume response data to free up memory162 response.resume();163 fulfill({164 error165 });166 return;167 }168 const file = _fs.default.createWriteStream(destinationPath);169 file.on('finish', () => fulfill({170 error: null171 }));172 file.on('error', error => fulfill({173 error174 }));175 response.pipe(file);176 totalBytes = parseInt(response.headers['content-length'] || '0', 10);177 log(`-- total bytes: ${totalBytes}`);178 if (progressCallback) response.on('data', onData);179 }, error => fulfill({180 error181 }));182 return promise;183 function onData(chunk) {184 downloadedBytes += chunk.length;185 progressCallback(downloadedBytes, totalBytes);186 }187}188async function download(url, destination, options = {}) {189 const {190 progressBarName = 'file',191 retryCount = 3,192 log = () => {},193 userAgent194 } = options;195 for (let attempt = 1; attempt <= retryCount; ++attempt) {196 log(`downloading ${progressBarName} - attempt #${attempt}`);197 const {198 error199 } = await downloadFile(url, destination, {200 progressCallback: getDownloadProgress(progressBarName),201 log,202 userAgent203 });204 if (!error) {205 log(`SUCCESS downloading ${progressBarName}`);206 break;207 }208 const errorMessage = (error === null || error === void 0 ? void 0 : error.message) || '';209 log(`attempt #${attempt} - ERROR: ${errorMessage}`);210 if (attempt < retryCount && (errorMessage.includes('ECONNRESET') || errorMessage.includes('ETIMEDOUT'))) {211 // Maximum default delay is 3rd retry: 1337.5ms212 const millis = Math.random() * 200 + 250 * Math.pow(1.5, attempt);213 log(`sleeping ${millis}ms before retry...`);214 await new Promise(c => setTimeout(c, millis));215 } else {216 throw error;217 }218 }219}220function getDownloadProgress(progressBarName) {221 let progressBar;222 let lastDownloadedBytes = 0;223 return (downloadedBytes, totalBytes) => {224 if (!process.stderr.isTTY) return;225 if (!progressBar) {226 progressBar = new _progress.default(`Downloading ${progressBarName} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {227 complete: '=',228 incomplete: ' ',229 width: 20,230 total: totalBytes231 });232 }233 const delta = downloadedBytes - lastDownloadedBytes;234 lastDownloadedBytes = downloadedBytes;235 progressBar.tick(delta);236 };237}238function toMegabytes(bytes) {239 const mb = bytes / 1024 / 1024;240 return `${Math.round(mb * 10) / 10} Mb`;241}242function spawnAsync(cmd, args, options = {}) {243 const process = (0, _child_process.spawn)(cmd, args, options);244 return new Promise(resolve => {245 let stdout = '';246 let stderr = '';247 if (process.stdout) process.stdout.on('data', data => stdout += data);248 if (process.stderr) process.stderr.on('data', data => stderr += data);249 process.on('close', code => resolve({250 stdout,251 stderr,252 code253 }));254 process.on('error', error => resolve({255 stdout,256 stderr,257 code: 0,258 error259 }));260 });261} // See https://joel.tools/microtasks/262function makeWaitForNextTask() {263 // As of Mar 2021, Electorn v12 doesn't create new task with `setImmediate` despite264 // using Node 14 internally, so we fallback to `setTimeout(0)` instead.265 // @see https://github.com/electron/electron/issues/28261266 if (process.versions.electron) return callback => setTimeout(callback, 0);267 if (parseInt(process.versions.node, 10) >= 11) return setImmediate; // Unlike Node 11, Node 10 and less have a bug with Task and MicroTask execution order:268 // - https://github.com/nodejs/node/issues/22257269 //270 // So we can't simply run setImmediate to dispatch code in a following task.271 // However, we can run setImmediate from-inside setImmediate to make sure we're getting272 // in the following task.273 let spinning = false;274 const callbacks = [];275 const loop = () => {276 const callback = callbacks.shift();277 if (!callback) {278 spinning = false;279 return;280 }281 setImmediate(loop); // Make sure to call callback() as the last thing since it's282 // untrusted code that might throw.283 callback();284 };285 return callback => {286 callbacks.push(callback);287 if (!spinning) {288 spinning = true;289 setImmediate(loop);290 }291 };292}293function assert(value, message) {294 if (!value) throw new Error(message || 'Assertion error');295}296function debugAssert(value, message) {297 if (isUnderTest() && !value) throw new Error(message);298}299function isString(obj) {300 return typeof obj === 'string' || obj instanceof String;301}302function isRegExp(obj) {303 return obj instanceof RegExp || Object.prototype.toString.call(obj) === '[object RegExp]';304}305function isObject(obj) {306 return typeof obj === 'object' && obj !== null;307}308function isError(obj) {309 return obj instanceof Error || obj && obj.__proto__ && obj.__proto__.name === 'Error';310}311const debugEnv = getFromENV('PWDEBUG') || '';312function debugMode() {313 if (debugEnv === 'console') return 'console';314 return debugEnv ? 'inspector' : '';315}316let _isUnderTest = false;317function setUnderTest() {318 _isUnderTest = true;319}320function isUnderTest() {321 return _isUnderTest;322}323function getFromENV(name) {324 let value = process.env[name];325 value = value === undefined ? process.env[`npm_config_${name.toLowerCase()}`] : value;326 value = value === undefined ? process.env[`npm_package_config_${name.toLowerCase()}`] : value;327 return value;328}329function getAsBooleanFromENV(name) {330 const value = getFromENV(name);331 return !!value && value !== 'false' && value !== '0';332}333async function mkdirIfNeeded(filePath) {334 // This will harmlessly throw on windows if the dirname is the root directory.335 await _fs.default.promises.mkdir(_path.default.dirname(filePath), {336 recursive: true337 }).catch(() => {});338}339function headersObjectToArray(headers, separator, setCookieSeparator) {340 if (!setCookieSeparator) setCookieSeparator = separator;341 const result = [];342 for (const name in headers) {343 const values = headers[name];344 if (separator) {345 const sep = name.toLowerCase() === 'set-cookie' ? setCookieSeparator : separator;346 for (const value of values.split(sep)) result.push({347 name,348 value: value.trim()349 });350 } else {351 result.push({352 name,353 value: values354 });355 }356 }357 return result;358}359function headersArrayToObject(headers, lowerCase) {360 const result = {};361 for (const {362 name,363 value364 } of headers) result[lowerCase ? name.toLowerCase() : name] = value;365 return result;366}367function monotonicTime() {368 const [seconds, nanoseconds] = process.hrtime();369 return seconds * 1000 + (nanoseconds / 1000 | 0) / 1000;370}371function objectToArray(map) {372 if (!map) return undefined;373 const result = [];374 for (const [name, value] of Object.entries(map)) result.push({375 name,376 value: String(value)377 });378 return result;379}380function arrayToObject(array) {381 if (!array) return undefined;382 const result = {};383 for (const {384 name,385 value386 } of array) result[name] = value;387 return result;388}389function calculateSha1(buffer) {390 const hash = crypto.createHash('sha1');391 hash.update(buffer);392 return hash.digest('hex');393}394function createGuid() {395 return crypto.randomBytes(16).toString('hex');396}397async function removeFolders(dirs) {398 return await Promise.all(dirs.map(dir => {399 return new Promise(fulfill => {400 (0, _rimraf.default)(dir, {401 maxBusyTries: 10402 }, error => {403 fulfill(error !== null && error !== void 0 ? error : undefined);404 });405 });406 }));407}408function canAccessFile(file) {409 if (!file) return false;410 try {411 _fs.default.accessSync(file);412 return true;413 } catch (e) {414 return false;415 }416}417let cachedUserAgent;418function getUserAgent() {419 if (cachedUserAgent) return cachedUserAgent;420 try {421 cachedUserAgent = determineUserAgent();422 } catch (e) {423 cachedUserAgent = 'Playwright/unknown';424 }425 return cachedUserAgent;426}427function determineUserAgent() {428 let osIdentifier = 'unknown';429 let osVersion = 'unknown';430 if (process.platform === 'win32') {431 const version = _os.default.release().split('.');432 osIdentifier = 'windows';433 osVersion = `${version[0]}.${version[1]}`;434 } else if (process.platform === 'darwin') {435 const version = (0, _child_process.execSync)('sw_vers -productVersion').toString().trim().split('.');436 osIdentifier = 'macOS';437 osVersion = `${version[0]}.${version[1]}`;438 } else if (process.platform === 'linux') {439 try {440 // List of /etc/os-release values for different distributions could be441 // found here: https://gist.github.com/aslushnikov/8ceddb8288e4cf9db3039c02e0f4fb75442 const osReleaseText = _fs.default.readFileSync('/etc/os-release', 'utf8');443 const fields = (0, _ubuntuVersion.parseOSReleaseText)(osReleaseText);444 osIdentifier = fields.get('id') || 'unknown';445 osVersion = fields.get('version_id') || 'unknown';446 } catch (e) {447 // Linux distribution without /etc/os-release.448 // Default to linux/unknown.449 osIdentifier = 'linux';450 }451 }452 let langName = 'unknown';453 let langVersion = 'unknown';454 if (!process.env.PW_CLI_TARGET_LANG) {455 langName = 'node';456 langVersion = process.version.substring(1).split('.').slice(0, 2).join('.');457 } else if (['node', 'python', 'java', 'csharp'].includes(process.env.PW_CLI_TARGET_LANG)) {458 var _process$env$PW_CLI_T;459 langName = process.env.PW_CLI_TARGET_LANG;460 langVersion = (_process$env$PW_CLI_T = process.env.PW_CLI_TARGET_LANG_VERSION) !== null && _process$env$PW_CLI_T !== void 0 ? _process$env$PW_CLI_T : 'unknown';461 }462 return `Playwright/${getPlaywrightVersion()} (${_os.default.arch()}; ${osIdentifier} ${osVersion}) ${langName}/${langVersion}`;463}464function getPlaywrightVersion(majorMinorOnly = false) {465 const packageJson = require('./../../package.json');466 return majorMinorOnly ? packageJson.version.split('.').slice(0, 2).join('.') : packageJson.version;467}468function constructURLBasedOnBaseURL(baseURL, givenURL) {469 try {470 return new URL.URL(givenURL, baseURL).toString();471 } catch (e) {472 return givenURL;473 }474}475const hostPlatform = (() => {476 const platform = _os.default.platform();477 if (platform === 'darwin') {478 const ver = _os.default.release().split('.').map(a => parseInt(a, 10));479 let macVersion = '';480 if (ver[0] < 18) {481 // Everything before 10.14 is considered 10.13.482 macVersion = 'mac10.13';483 } else if (ver[0] === 18) {484 macVersion = 'mac10.14';485 } else if (ver[0] === 19) {486 macVersion = 'mac10.15';487 } else {488 // ver[0] >= 20489 const LAST_STABLE_MAC_MAJOR_VERSION = 12; // Best-effort support for MacOS beta versions.490 macVersion = 'mac' + Math.min(ver[0] - 9, LAST_STABLE_MAC_MAJOR_VERSION); // BigSur is the first version that might run on Apple Silicon.491 if (_os.default.cpus().some(cpu => cpu.model.includes('Apple'))) macVersion += '-arm64';492 }493 return macVersion;494 }495 if (platform === 'linux') {496 const ubuntuVersion = (0, _ubuntuVersion.getUbuntuVersionSync)();497 const archSuffix = _os.default.arch() === 'arm64' ? '-arm64' : '';498 if (parseInt(ubuntuVersion, 10) <= 19) return 'ubuntu18.04' + archSuffix;499 return 'ubuntu20.04' + archSuffix;500 }501 if (platform === 'win32') return 'win64';502 return platform;503})();504exports.hostPlatform = hostPlatform;505function wrapInASCIIBox(text, padding = 0) {506 const lines = text.split('\n');507 const maxLength = Math.max(...lines.map(line => line.length));508 return ['╔' + '═'.repeat(maxLength + padding * 2) + '╗', ...lines.map(line => '║' + ' '.repeat(padding) + line + ' '.repeat(maxLength - line.length + padding) + '║'), '╚' + '═'.repeat(maxLength + padding * 2) + '╝'].join('\n');509}510function isFilePayload(value) {511 return typeof value === 'object' && value['name'] && value['mimeType'] && value['buffer'];512}513function streamToString(stream) {514 return new Promise((resolve, reject) => {515 const chunks = [];516 stream.on('data', chunk => chunks.push(Buffer.from(chunk)));517 stream.on('error', reject);518 stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));519 });520}521async function transformCommandsForRoot(commands) {522 const isRoot = process.getuid() === 0;523 if (isRoot) return {524 command: 'sh',525 args: ['-c', `${commands.join('&& ')}`],526 elevatedPermissions: false527 };528 const sudoExists = await spawnAsync('which', ['sudo']);529 if (sudoExists.code === 0) return {530 command: 'sudo',531 args: ['--', 'sh', '-c', `${commands.join('&& ')}`],532 elevatedPermissions: true533 };534 return {535 command: 'su',536 args: ['root', '-c', `${commands.join('&& ')}`],537 elevatedPermissions: true538 };...

Full Screen

Full Screen

ubuntuVersion.js

Source:ubuntuVersion.js Github

copy

Full Screen

...52 } catch (e) {53 return '';54 }55}56function parseOSReleaseText(osReleaseText) {57 const fields = new Map();58 for (const line of osReleaseText.split('\n')) {59 const tokens = line.split('=');60 const name = tokens.shift();61 let value = tokens.join('=').trim();62 if (value.startsWith('"') && value.endsWith('"')) value = value.substring(1, value.length - 1);63 if (!name) continue;64 fields.set(name.toLowerCase(), value);65 }66 return fields;67}68function parseUbuntuVersion(osReleaseText) {69 var _fields$get, _fields$get2;70 const fields = parseOSReleaseText(osReleaseText); // For Linux mint71 if (fields.get('distrib_id') && ((_fields$get = fields.get('distrib_id')) === null || _fields$get === void 0 ? void 0 : _fields$get.toLowerCase()) === 'ubuntu') return fields.get('distrib_release') || '';72 if (!fields.get('name') || ((_fields$get2 = fields.get('name')) === null || _fields$get2 === void 0 ? void 0 : _fields$get2.toLowerCase()) !== 'ubuntu') return '';73 return fields.get('version_id') || '';...

Full Screen

Full Screen

userAgent.js

Source:userAgent.js Github

copy

Full Screen

1"use strict";2Object.defineProperty(exports, "__esModule", {3 value: true4});5exports.getClientLanguage = getClientLanguage;6exports.getPlaywrightVersion = getPlaywrightVersion;7exports.getUserAgent = getUserAgent;8var _child_process = require("child_process");9var _fs = _interopRequireDefault(require("fs"));10var _os = _interopRequireDefault(require("os"));11var _ubuntuVersion = require("../utils/ubuntuVersion");12function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }13/**14 * Copyright (c) Microsoft Corporation.15 *16 * Licensed under the Apache License, Version 2.0 (the "License");17 * you may not use this file except in compliance with the License.18 * You may obtain a copy of the License at19 *20 * http://www.apache.org/licenses/LICENSE-2.021 *22 * Unless required by applicable law or agreed to in writing, software23 * distributed under the License is distributed on an "AS IS" BASIS,24 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.25 * See the License for the specific language governing permissions and26 * limitations under the License.27 */28let cachedUserAgent;29function getUserAgent() {30 if (cachedUserAgent) return cachedUserAgent;31 try {32 cachedUserAgent = determineUserAgent();33 } catch (e) {34 cachedUserAgent = 'Playwright/unknown';35 }36 return cachedUserAgent;37}38function determineUserAgent() {39 let osIdentifier = 'unknown';40 let osVersion = 'unknown';41 if (process.platform === 'win32') {42 const version = _os.default.release().split('.');43 osIdentifier = 'windows';44 osVersion = `${version[0]}.${version[1]}`;45 } else if (process.platform === 'darwin') {46 const version = (0, _child_process.execSync)('sw_vers -productVersion', {47 stdio: ['ignore', 'pipe', 'ignore']48 }).toString().trim().split('.');49 osIdentifier = 'macOS';50 osVersion = `${version[0]}.${version[1]}`;51 } else if (process.platform === 'linux') {52 try {53 // List of /etc/os-release values for different distributions could be54 // found here: https://gist.github.com/aslushnikov/8ceddb8288e4cf9db3039c02e0f4fb7555 const osReleaseText = _fs.default.readFileSync('/etc/os-release', 'utf8');56 const fields = (0, _ubuntuVersion.parseOSReleaseText)(osReleaseText);57 osIdentifier = fields.get('id') || 'unknown';58 osVersion = fields.get('version_id') || 'unknown';59 } catch (e) {60 // Linux distribution without /etc/os-release.61 // Default to linux/unknown.62 osIdentifier = 'linux';63 }64 }65 const {66 langName,67 langVersion68 } = getClientLanguage();69 return `Playwright/${getPlaywrightVersion()} (${_os.default.arch()}; ${osIdentifier} ${osVersion}) ${langName}/${langVersion}`;70}71function getClientLanguage() {72 let langName = 'unknown';73 let langVersion = 'unknown';74 if (!process.env.PW_LANG_NAME) {75 langName = 'node';76 langVersion = process.version.substring(1).split('.').slice(0, 2).join('.');77 } else if (['node', 'python', 'java', 'csharp'].includes(process.env.PW_LANG_NAME)) {78 var _process$env$PW_LANG_;79 langName = process.env.PW_LANG_NAME;80 langVersion = (_process$env$PW_LANG_ = process.env.PW_LANG_NAME_VERSION) !== null && _process$env$PW_LANG_ !== void 0 ? _process$env$PW_LANG_ : 'unknown';81 }82 return {83 langName,84 langVersion85 };86}87function getPlaywrightVersion(majorMinorOnly = false) {88 const packageJson = require('./../../package.json');89 return majorMinorOnly ? packageJson.version.split('.').slice(0, 2).join('.') : packageJson.version;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseOSReleaseText } = require('playwright/lib/utils/utils');2VERSION="20.04.2 LTS (Focal Fossa)"3UBUNTU_CODENAME=focal`;4const parsed = parseOSReleaseText(osReleaseText);5console.log(parsed);6const { parseLsbReleaseText } = require('playwright/lib/utils/utils');7DISTRIB_DESCRIPTION="Ubuntu 20.04.2 LTS"`;8const parsed = parseLsbReleaseText(lsbReleaseText);9console.log(parsed);10const { parseProcVersionText } = require('playwright/lib/utils/utils');11const procVersionText = 'Linux version 5.4.0-74-generic (buildd@lcy01-amd64-030) (gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)) #83-Ubuntu SMP Fri Mar 19 12:02:54 UTC 2021';12const parsed = parseProcVersionText(procVersionText);13console.log(parsed);14const { parseCpuInfoText } = require('playwright/lib/utils/utils');15model name : Intel(R) Core(TM) i7-9750H CPU @

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseOSReleaseText } = require('playwright/lib/server/utils');2VERSION="20.04.2 LTS (Focal Fossa)"3`;4const parsedData = parseOSReleaseText(osReleaseText);5console.log(parsedData);6const { parseOSReleaseText } = require('playwright/lib/server/utils');7VERSION="20.04.2 LTS (Focal Fossa)"8`;9const parsedData = parseOSReleaseText(osReleaseText);10console.log(parsedData);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseOSReleaseText } = require('playwright/lib/utils/utils');2VERSION="20.04.2 LTS (Focal Fossa)"3`;4console.log(parseOSReleaseText(osReleaseText));5{6 VERSION: '20.04.2 LTS (Focal Fossa)',7}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseOSReleaseText } = require('playwright/lib/server/utils');2VERSION="18.04.4 LTS (Bionic Beaver)"3UBUNTU_CODENAME=bionic`;4const parsedOSRelease = parseOSReleaseText(osRelease);5console.log(parsedOSRelease);6const { parseOSReleaseFile } = require('playwright/lib/server/utils');7const parsedOSReleaseFile = parseOSReleaseFile('/etc/os-release');8console.log(parsedOSReleaseFile);9{10 version: '18.04.4 LTS (Bionic Beaver)',11}12{13 version: '18.04.4 LTS (Bionic Beaver)',14}15Your name to display (optional):16Your name to display (optional

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseOSReleaseText } = require('playwright/lib/server/registry');2VERSION="18.04.5 LTS (Bionic Beaver)"3UBUNTU_CODENAME=bionic`;4const osReleaseInfo = parseOSReleaseText(osReleaseText);5console.log(osReleaseInfo);6The parseOSReleaseText() method is located at the following path:7The parseOSReleaseText() method is located at the following path:8const { parseOSReleaseText } = require('playwright/lib/server/registry');9const os = require('os');10const osReleaseInfo = parseOSReleaseText(os.release());11console.log(osReleaseInfo);12The parseOSReleaseText() method is located at the following path:13The parseOSReleaseText() method is located at the following path:14The parseOSReleaseText() method can be used to parse the /etc/os-release file on Linux machines. The method returns an object containing the name and version of

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseOSReleaseText } = require('playwright/lib/server/browserType');2const { osRelease } = require('playwright/lib/utils/utils');3const osReleaseText = osRelease();4const parsed = parseOSReleaseText(osReleaseText);5console.log(parsed);6{ ID: 'ubuntu',7 VERSION: '20.04.1 LTS (Focal Fossa)',8 UBUNTU_CODENAME: 'focal' }9const { parseOSReleaseText } = require('playwright/lib/server/browserType');10const { readFileSync } = require('fs');11const { resolve } = require('path');12const osReleaseText = readFileSync(resolve(process.cwd(), 'os-release'), 'utf8');13const parsed = parseOSReleaseText(osReleaseText);14console.log(parsed);15{ ID: 'ubuntu',16 VERSION: '20.04.1 LTS (Focal Fossa)',17 UBUNTU_CODENAME: 'focal' }

Full Screen

Using AI Code Generation

copy

Full Screen

1const { parseOSReleaseText } = require('playwright/lib/server/parseOSRelease');2{ NAME: 'Ubuntu',3 VERSION: '20.04.1 LTS (Focal Fossa)',4 UBUNTU_CODENAME: 'focal' }5VERSION="18.04.5 LTS (Bionic Beaver)"6{ NAME: 'Ubuntu',7 VERSION: '18.04.5 LTS (Bionic Beaver)',

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful