Best JavaScript code snippet using playwright-internal
dashboard_compressed_v1.js
Source:dashboard_compressed_v1.js
...16const {SimpleBlob, flattenSpecs} = require('./utils.js');17async function processDashboardCompressedV1(context, reports, commitSHA) {18 const timestamp = Date.now();19 const dashboardBlob = await SimpleBlob.create('dashboards', `compressed_v1/${commitSHA}.json`);20 await dashboardBlob.uploadGzipped(compressReports(reports));21 context.log(`22 ===== started dashboard compressed v1 =====23 SHA: ${commitSHA}24 ===== complete in ${Date.now() - timestamp}ms =====25 `);26}27module.exports = {processDashboardCompressedV1, compressReports};28function compressReports(reports) {29 const files = {};30 for (const report of reports) {31 for (const spec of flattenSpecs(report)) {32 let specs = files[spec.file];33 if (!specs) {34 specs = new Map();35 files[spec.file] = specs;36 }37 const specId = spec.file + '---' + spec.title + ' --- ' + spec.line;38 let specObject = specs.get(specId);39 if (!specObject) {40 specObject = {41 title: spec.title,42 line: spec.line,...
healthcheck.js
Source:healthcheck.js
...40 };41 }42 return merged;43}44function compressReports(reports) {45 const compressed = [];46 for (var i = 0; i < reports.length; i++) {47 let report = reports[i];48 let compressedReport = [];49 for (let name of services) {50 let serviceReport = report[name];51 if (!serviceReport) {52 compressedReport.push(null);53 continue;54 }55 compressedReport.push([56 serviceReport.ping,57 serviceReport.success,58 serviceReport.errors,59 ]);60 }61 compressed.push(compressedReport);62 }63 return compressed;64}65function parsePings(pings) {66 let report = {};67 // format with structure68 // {69 // "service": {70 // "success": 0,71 // "errors": 0,72 // "ping": average73 // }74 // }75 const workers = Object.keys(pings);76 for (let i = 0; i < workers.length; i++) {77 const [service, worker] = workers[i].split("@", 2);78 let ping = pings[ workers[i] ];79 if (!report[service]) {80 report[service] = {81 count: 1,82 ...ping,83 };84 } else {85 report[service].count += 1;86 report[service].ping += ping.ping;87 report[service].success += ping.success;88 report[service].errors += ping.errors;89 }90 }91 let unknownServices = [];92 const serviceKeys = Object.keys(report);93 for (let i = 0; i < serviceKeys.length; i++) {94 const service = serviceKeys[i];95 if (!services.includes(service)) {96 unknownServices.push(service);97 }98 report[service].ping = report[service].ping / report[service].count;99 delete report[service].count;100 }101 return [ report, unknownServices ];102}103// Triggered when this service sends a ping request and it gets completed104service.onPing((responsible, pings) => {105 const [ report, unknownServices ] = parsePings(pings);106 if (unknownServices.length > 0) {107 for (let i = 0; i < unknownServices.length; i++) {108 services.push(unknownServices[i]);109 }110 if (responsible) {111 service.redis.sadd("status:services", unknownServices, (err) => {112 if (!!err) {113 console.log(err);114 }115 });116 }117 }118 nextGroup.push(report);119 if (nextGroup.length >= reportsPerGroup) {120 if (responsible) {121 const group = mergeReports(nextGroup);122 service.redis.rpush(123 "status:reports",124 JSON.stringify(group),125 (err, items) => {126 if (!!err) {127 console.error(err);128 return;129 }130 if (items > historySize) {131 service.redis.lpop(132 "status:reports",133 items - historySize,134 (err) => {135 if (!!err) {136 console.error(err);137 return;138 }139 }140 );141 }142 }143 );144 }145 nextGroup = [];146 }147 toSend = {148 services,149 data: compressReports([report])[0],150 };151 let forWS = JSON.stringify(toSend);152 // Notify all the clients listening for this event153 for (let i = 0; i < statusListeners.length; i++) {154 statusListeners[i].send(forWS);155 }156});157// A new client wants to listen to service status158router.ws("/status", (ws, req) => {159 statusListeners.push(ws); // Register the client160 ws.on("close", () => {161 // The client disconnected. Remove from list.162 let index = statusListeners.indexOf(ws);163 statusListeners.splice(index, 1);164 });165});166router.get("/status/current", (req, res) => {167 res.send(toSend);168});169router.get("/status/past", (req, res) => {170 let { interval } = req.query;171 interval = parseInt(interval) || 2;172 if (interval > 12) {173 writeError(res, 400, "Requested interval is too big.");174 return;175 }176 service.redis.lrange("status:reports", 0, -1, (err, result) => {177 if (!!err) {178 console.error(err);179 writeError(res, 500);180 return;181 }182 let reports = [];183 let forInterval = [];184 if (interval > 1) {185 // Some intervals are skipped, so let's merge them186 for (let i = 0; i < result.length; i++) {187 forInterval.push(JSON.parse(result[i]));188 if (i > 0 && ((i + 1) % interval === 0)) {189 reports.push(mergeReports(forInterval));190 forInterval = [];191 }192 }193 forInterval = compressReports(forInterval);194 } else {195 for (let i = 0; i < result.length; i++) {196 reports.push(JSON.parse(result[i]));197 }198 }199 res.send({200 interval,201 services,202 forInterval,203 data: compressReports(reports)204 });205 });206});...
scan.js
Source:scan.js
...21 // }22 // console.log(`all scans complete`);23 // console.log(`compressing reports`);24 await combineJSON();25 // await compressReports();26 console.log(`reports compressed`);27}28async function fetchURLs() {29 const docURL = config.docURL;30 console.log(`requesting list of URLs to scan from ${docURL}`);31 const rsp = await fetch(docURL);32 const text = await rsp.text();33 return text.split(/\s+/);34}35// The shell version36async function lighthoose(37 url,38 date,39 config,40 opts = { chromeFlags: ["--headless", "--no-sandbox"] }41) {42 console.log(`scan starting on ${url}`);43 const happyUrl = url.replace(/[^A-z0-9]/g, "_");44 const outputDir = path.resolve(config.saveReportPath, happyUrl, date);45 const outputPath = path.resolve(outputDir, "lighthoose");46 // create reports dir47 await fs.ensureDir(outputDir);48 const onOpenshift = !!process.env.OPENSHIFT_BUILD_NAME;49 const openshiftCpuSlowdownMultiplier = 1;50 if (onOpenshift) {51 console.log(52 `detected openshift environment, setting CPU slowdown factor to ${1 /53 openshiftCpuSlowdownMultiplier}`54 );55 }56 const cmd = [57 `./node_modules/.bin/lighthouse`,58 `--chrome-flags="${opts.chromeFlags.join(" ")}"`,59 `--no-sandbox`,60 onOpenshift61 ? `--throttling.cpuSlowdownMultiplier=${openshiftCpuSlowdownMultiplier}`62 : "",63 `--output=json`,64 `--output=html`,65 `--output=csv`,66 `--output-path=${outputPath}`,67 `"${url}"`68 ].join(" ");69 try {70 const cmdOut = await shell(cmd);71 } catch (e) {72 console.log(`could not run lighthouse`);73 throw e;74 }75 console.log(`scan ${scanId} complete, report saved in ${outputDir}`);76}77async function combineJSON() {78 const reportPath = path.resolve(__dirname, config.saveReportPath);79 // properties of lighthouse JSON that we want to surface to the UI80 const INCLUDED_PROPS = [81 "audits.first-contentful-paint",82 "audits.first-meaningful-paint",83 "audits.speed-index"84 ];85 // properties of the lighthouse JSON that we don't want to surface to the86 // UI (essentially, sub-properties of INCLUDED_PROPS that we want to omit)87 const EXCLUDED_SUB_PROPS = _.flatten(88 ["displayValue", "id", "description", "scoreDisplayMode", "title"].map(sp =>89 INCLUDED_PROPS.map(ip => `${ip}.${sp}`)90 )91 );92 const jsonFiles = await globby(93 path.join(reportPath, "**", "lighthoose.report.json")94 );95 const combinedJSON = jsonFiles.map(require);96 // pick only the properties we care about for the UI97 const data = _(combinedJSON)98 .map(o =>99 _(o)100 .pick(INCLUDED_PROPS)101 .omit(EXCLUDED_SUB_PROPS)102 .value()103 )104 .value();105 // grab a copy of a few properties that were previously duplicated, for lookup in the UI106 const legend = _.pick(107 _.first(combinedJSON),108 _.flatten(INCLUDED_PROPS.map(ip => [`${ip}.description`, `${ip}.title`]))109 );110 await fs.writeJson(path.join(reportPath, "lighthoose.history.json"), {111 data,112 legend113 });114}115async function compressReports() {116 const reportPath = path.resolve(__dirname, config.saveReportPath);117 await zipdirp(reportPath, {118 saveTo: path.join(reportPath, "lighthoose-reports-all.zip"),119 filter: path => !/\.zip$/.test(path) // don't include existing zip files120 });121}122module.exports = scan;123if (require.main === module) {124 scan();...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 await context.tracing.start({ screenshots: true, snapshots: true });6 const page = await context.newPage();7 await context.tracing.stop({ path: 'trace.zip' });8 await browser.close();9})();10#### tracing.start(options)
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: 'example.png' });7 await browser.close();8 await context._browserContext._options.recordVideo._recorder._video._compressReports();9})();
Using AI Code Generation
1const fs = require('fs');2const path = require('path');3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'example.png' });9 const reportsDirectory = path.join(__dirname, 'reports');10 const compressedReportsDirectory = path.join(__dirname, 'compressed-reports');11 await page.context().compressReports(reportsDirectory, compressedReportsDirectory);12 await browser.close();13})();14#### browserContext.compressReports(reportsDirectory, compressedReportsDirectory[, options])15const fs = require('fs');16const path = require('path');17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: 'example.png' });23 const reportsDirectory = path.join(__dirname, 'reports');24 const compressedReportsDirectory = path.join(__dirname, 'compressed-reports');25 await page.context().compressReports(reportsDirectory, compressedReportsDirectory);26 await browser.close();27})();28const fs = require('fs');29const path = require('path');30const { chromium } = require('playwright');31(async () => {32 const browser = await chromium.launch();
Using AI Code Generation
1const { compressReports } = require('@playwright/test');2(async () => {3 await compressReports({4 });5})();6### method: `compressReports(options)`7[Apache 2.0](LICENSE)
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.
Get 100 minutes of automation test minutes FREE!!