Best JavaScript code snippet using wpt
reporting-common.js
Source:reporting-common.js
1const executor_path = "/common/dispatcher/executor.html?pipe=";2const coep_header = '|header(Cross-Origin-Embedder-Policy,require-corp)';3const isWPTSubEnabled = "{{GET[pipe]}}".includes("sub");4const getReportEndpointURL = (reportID) =>5 `/reporting/resources/report.py?reportID=${reportID}`;6const reportEndpoint = {7 name: "coop-report-endpoint",8 reportID: isWPTSubEnabled ? "{{GET[report_id]}}" : token(),9 reports: []10};11const reportOnlyEndpoint = {12 name: "coop-report-only-endpoint",13 reportID: isWPTSubEnabled ? "{{GET[report_only_id]}}" : token(),14 reports: []15};16const popupReportEndpoint = {17 name: "coop-popup-report-endpoint",18 reportID: token(),19 reports: []20};21const popupReportOnlyEndpoint = {22 name: "coop-popup-report-only-endpoint",23 reportID: token(),24 reports: []25};26const redirectReportEndpoint = {27 name: "coop-redirect-report-endpoint",28 reportID: token(),29 reports: []30};31const redirectReportOnlyEndpoint = {32 name: "coop-redirect-report-only-endpoint",33 reportID: token(),34 reports: []35};36const reportEndpoints = [37 reportEndpoint,38 reportOnlyEndpoint,39 popupReportEndpoint,40 popupReportOnlyEndpoint,41 redirectReportEndpoint,42 redirectReportOnlyEndpoint43];44// Allows RegExps to be pretty printed when printing unmatched expected reports.45Object.defineProperty(RegExp.prototype, "toJSON", {46 value: RegExp.prototype.toString47});48function wait(ms) {49 return new Promise(resolve => step_timeout(resolve, ms));50}51// Check whether a |report| is a "opener breakage" COOP report.52function isCoopOpenerBreakageReport(report) {53 if (report.type != "coop")54 return false;55 if (report.body.type != "navigation-from-response" &&56 report.body.type != "navigation-to-response") {57 return false;58 }59 return true;60}61async function clearReportsOnServer(host) {62 const res = await fetch(63 '/reporting/resources/report.py', {64 method: "POST",65 body: JSON.stringify({66 op: "DELETE",67 reportIDs: reportEndpoints.map(endpoint => endpoint.reportID)68 })69 });70 assert_equals(res.status, 200, "reports cleared");71}72async function pollReports(endpoint) {73 const res = await fetch(getReportEndpointURL(endpoint.reportID),74 { cache: 'no-store' });75 if (res.status !== 200) {76 return;77 }78 for (const report of await res.json()) {79 if (isCoopOpenerBreakageReport(report))80 endpoint.reports.push(report);81 }82}83// Recursively check that all members of expectedReport are present or matched84// in report.85// Report may have members not explicitly expected by expectedReport.86function isObjectAsExpected(report, expectedReport) {87 if (( report === undefined || report === null88 || expectedReport === undefined || expectedReport === null )89 && report !== expectedReport ) {90 return false;91 }92 if (expectedReport instanceof RegExp && typeof report === "string") {93 return expectedReport.test(report);94 }95 // Perform this check now, as RegExp and strings above have different typeof.96 if (typeof report !== typeof expectedReport)97 return false;98 if (typeof expectedReport === 'object') {99 return Object.keys(expectedReport).every(key => {100 return isObjectAsExpected(report[key], expectedReport[key]);101 });102 }103 return report == expectedReport;104}105async function checkForExpectedReport(expectedReport) {106 return new Promise( async (resolve, reject) => {107 const polls = 20;108 const waitTime = 200;109 for (var i=0; i < polls; ++i) {110 pollReports(expectedReport.endpoint);111 for (var j=0; j<expectedReport.endpoint.reports.length; ++j){112 if (isObjectAsExpected(expectedReport.endpoint.reports[j],113 expectedReport.report)){114 expectedReport.endpoint.reports.splice(j,1);115 resolve();116 return;117 }118 };119 await wait(waitTime);120 }121 reject(122 replaceTokensInReceivedReport(123 "No report matched the expected report for endpoint: "124 + expectedReport.endpoint.name125 + ", expected report: " + JSON.stringify(expectedReport.report)126 + ", within available reports: "127 + JSON.stringify(expectedReport.endpoint.reports)128 ));129 });130}131function replaceFromRegexOrString(str, match, value) {132 if (str instanceof RegExp) {133 return RegExp(str.source.replace(match, value));134 }135 return str.replace(match, value);136}137// Replace generated values in regexes and strings of an expected report:138// EXECUTOR_UUID: the uuid generated with token().139function replaceValuesInExpectedReport(expectedReport, executorUuid) {140 if (expectedReport.report.body !== undefined) {141 if (expectedReport.report.body.nextResponseURL !== undefined) {142 expectedReport.report.body.nextResponseURL = replaceFromRegexOrString(143 expectedReport.report.body.nextResponseURL, "EXECUTOR_UUID",144 executorUuid);145 }146 if (expectedReport.report.body.previousResponseURL !== undefined) {147 expectedReport.report.body.previousResponseURL = replaceFromRegexOrString(148 expectedReport.report.body.previousResponseURL, "EXECUTOR_UUID",149 executorUuid);150 }151 if (expectedReport.report.body.referrer !== undefined) {152 expectedReport.report.body.referrer = replaceFromRegexOrString(153 expectedReport.report.body.referrer, "EXECUTOR_UUID",154 executorUuid);155 }156 }157 if (expectedReport.report.url !== undefined) {158 expectedReport.report.url = replaceFromRegexOrString(159 expectedReport.report.url, "EXECUTOR_UUID", executorUuid);160 }161 return expectedReport;162}163function replaceTokensInReceivedReport(str) {164 return str.replace(/.{8}-.{4}-.{4}-.{4}-.{12}/g, `(uuid)`);165}166// Run a test then check that all expected reports are present.167async function reportingTest(testFunction, executorToken, expectedReports) {168 await new Promise(testFunction);169 expectedReports = Array.from(170 expectedReports,171 report => replaceValuesInExpectedReport(report, executorToken) );172 await Promise.all(Array.from(expectedReports, checkForExpectedReport));173}174function convertToWPTHeaderPipe([name, value]) {175 return `header(${name}, ${encodeURIComponent(value)})`;176}177function getReportToHeader(host) {178 return [179 "Report-To",180 reportEndpoints.map(181 reportEndpoint => {182 const reportToJSON = {183 'group': `${reportEndpoint.name}`,184 'max_age': 3600,185 'endpoints': [{186 'url': `${host}${getReportEndpointURL(reportEndpoint.reportID)}`187 }]188 };189 // Escape comma as required by wpt pipes.190 return JSON.stringify(reportToJSON)191 .replace(/,/g, '\\,')192 .replace(/\(/g, '\\\(')193 .replace(/\)/g, '\\\)=');194 }195 ).join("\\, ")];196}197function getReportingEndpointsHeader(host) {198 return [199 "Reporting-Endpoints",200 reportEndpoints.map(reportEndpoint => {201 return `${reportEndpoint.name}="${host}${getReportEndpointURL(reportEndpoint.reportID)}"`;202 }).join("\\, ")];203}204// Return Report and Report-Only policy headers.205function getPolicyHeaders(coop, coep, coopRo, coepRo) {206 return [207 [`Cross-Origin-Opener-Policy`, coop],208 [`Cross-Origin-Embedder-Policy`, coep],209 [`Cross-Origin-Opener-Policy-Report-Only`, coopRo],210 [`Cross-Origin-Embedder-Policy-Report-Only`, coepRo]];211}212function navigationReportingTest(testName, host, coop, coep, coopRo, coepRo,213 expectedReports) {214 const executorToken = token();215 const callbackToken = token();216 promise_test(async t => {217 await reportingTest(async resolve => {218 const openee_headers = [219 getReportingEndpointsHeader(host.origin),220 ...getPolicyHeaders(coop, coep, coopRo, coepRo)221 ].map(convertToWPTHeaderPipe);222 const openee_url = host.origin + executor_path +223 openee_headers.join('|') + `&uuid=${executorToken}`;224 const openee = window.open(openee_url);225 const uuid = token();226 t.add_cleanup(() => send(uuid, "window.close()"));227 // 1. Make sure the new document is loaded.228 send(executorToken, `229 send("${callbackToken}", "Ready");230 `);231 let reply = await receive(callbackToken);232 assert_equals(reply, "Ready");233 resolve();234 }, executorToken, expectedReports);235 }, `coop reporting test ${testName} to ${host.name} with ${coop}, ${coep}, ${coopRo}, ${coepRo}`);236}237function navigationDocumentReportingTest(testName, host, coop, coep, coopRo,238 coepRo, expectedReports) {239 const executorToken = token();240 const callbackToken = token();241 promise_test(async t => {242 const openee_headers = [243 getReportingEndpointsHeader(host.origin),244 ...getPolicyHeaders(coop, coep, coopRo, coepRo)245 ].map(convertToWPTHeaderPipe);246 const openee_url = host.origin + executor_path +247 openee_headers.join('|') + `&uuid=${executorToken}`;248 window.open(openee_url);249 t.add_cleanup(() => send(executorToken, "window.close()"));250 // Have openee window send a message through dispatcher, once we receive251 // the Ready message from dispatcher it means the openee is fully loaded.252 send(executorToken, `253 send("${callbackToken}", "Ready");254 `);255 let reply = await receive(callbackToken);256 assert_equals(reply, "Ready");257 await wait(1000);258 expectedReports = expectedReports.map(259 (report) => replaceValuesInExpectedReport(report, executorToken));260 return Promise.all(expectedReports.map(261 async ({ endpoint, report: expectedReport }) => {262 await pollReports(endpoint);263 for (let report of endpoint.reports) {264 assert_true(isObjectAsExpected(report, expectedReport),265 `report received for endpoint: ${endpoint.name} ${JSON.stringify(report)} should match ${JSON.stringify(expectedReport)}`);266 }267 assert_equals(endpoint.reports.length, 1, `has exactly one report for ${endpoint.name}`)268 }));269 }, `coop document reporting test ${testName} to ${host.name} with ${coop}, ${coep}, ${coopRo}, ${coepRo}`);270}271// Run an array of reporting tests then verify there's no reports that were not272// expected.273// Tests' elements contain: host, coop, coep, coop-report-only,274// coep-report-only, expectedReports.275// See isObjectAsExpected for explanations regarding the matching behavior.276async function runNavigationReportingTests(testName, tests) {277 await clearReportsOnServer();278 tests.forEach(test => {279 navigationReportingTest(testName, ...test);280 });281 verifyRemainingReports();282}283// Run an array of reporting tests using Reporting-Endpoints header then284// verify there's no reports that were not expected.285// Tests' elements contain: host, coop, coep, coop-report-only,286// coep-report-only, expectedReports.287// See isObjectAsExpected for explanations regarding the matching behavior.288function runNavigationDocumentReportingTests(testName, tests) {289 clearReportsOnServer();290 tests.forEach(test => {291 navigationDocumentReportingTest(testName, ...test);292 });293}294function verifyRemainingReports() {295 promise_test(t => {296 return Promise.all(reportEndpoints.map(async (endpoint) => {297 await pollReports(endpoint);298 assert_equals(endpoint.reports.length, 0, `${endpoint.name} should be empty`);299 }));300 }, "verify remaining reports");301}302const receiveReport = async function(uuid, type) {303 while(true) {304 let reports = await Promise.race([305 receive(uuid),306 new Promise(resolve => {307 step_timeout(resolve, 1000, "timeout");308 })309 ]);310 if (reports == "timeout")311 return "timeout";312 reports = JSON.parse(reports);313 for(report of reports) {314 if (report?.body?.type == type)315 return report;316 }317 }318}319// Build a set of 'Cross-Origin-Opener-Policy' and320// 'Cross-Origin-Opener-Policy-Report-Only' headers.321const coopHeaders = function (uuid) {322 return {323 coopSameOriginHeader: `|header(Cross-Origin-Opener-Policy,same-origin%3Breport-to="${uuid}")`,324 coopSameOriginAllowPopupsHeader: `|header(Cross-Origin-Opener-Policy,same-origin-allow-popups%3Breport-to="${uuid}")`,325 coopReportOnlySameOriginHeader: `|header(Cross-Origin-Opener-Policy-Report-Only,same-origin%3Breport-to="${uuid}")`,326 coopReportOnlySameOriginAllowPopupsHeader: `|header(Cross-Origin-Opener-Policy-Report-Only,same-origin-allow-popups%3Breport-to="${uuid}")`327 };328}329// Build a set of headers to tests the reporting API. This defines a set of330// matching 'Report-To', 'Cross-Origin-Opener-Policy' and331// 'Cross-Origin-Opener-Policy-Report-Only' headers.332const reportToHeaders = function(uuid) {333 const report_endpoint_url = dispatcher_path + `?uuid=${uuid}`;334 let reportToJSON = {335 'group': `${uuid}`,336 'max_age': 3600,337 'endpoints': [338 {'url': report_endpoint_url.toString()},339 ]340 };341 reportToJSON = JSON.stringify(reportToJSON)342 .replace(/,/g, '\\,')343 .replace(/\(/g, '\\\(')344 .replace(/\)/g, '\\\)=');345 return {346 header: `|header(report-to,${reportToJSON})`,347 ...coopHeaders(uuid)348 };349};350// Build a set of headers to tests the reporting API. This defines a set of351// matching 'Reporting-Endpoints', 'Cross-Origin-Opener-Policy' and352// 'Cross-Origin-Opener-Policy-Report-Only' headers.353const reportingEndpointsHeaders = function (uuid) {354 const report_endpoint_url = dispatcher_path + `?uuid=${uuid}`;355 const reporting_endpoints_header = `${uuid}="${report_endpoint_url}"`;356 return {357 header: `|header(Reporting-Endpoints,${reporting_endpoints_header})`,358 ...coopHeaders(uuid)359 };...
Using AI Code Generation
1var wpt = require('./wpt.js');2var wpt = new WebPageTest('www.webpagetest.org', 'API_KEY');3wpt.executorToken(function(err, data) {4 console.log(data);5});6WebPageTest.prototype.executorToken = function(callback) {7 var options = {8 };9 this._makeRequest(options, callback);10};11WebPageTest.prototype._makeRequest = function(options, callback) {12 var req = https.request(options, function(res) {13 var data = '';14 res.on('data', function(d) {15 data += d;16 });17 res.on('end', function() {18 if (res.statusCode === 200) {19 if (callback) {20 callback(null, JSON.parse(data));21 }22 } else {23 if (callback) {24 callback(new Error(data));25 }26 }27 });28 });29 req.on('error', function(e) {30 if (callback) {31 callback(e);32 }33 });34 req.end();35};
Using AI Code Generation
1var wpt = require('webpagetest');2var options = { key: 'A.12345678901234567890123456789012' };3var wpt = new WebPageTest('localhost', options);4wpt.runTest('www.google.com', function(err, data) {5 if (err) return console.log(err);6 console.log('Test Results: ' + data.data.userUrl);7 var testId = data.data.testId;8 wpt.getTestResults(testId, function(err, data) {9 if (err) return console.log(err);10 console.log('Test Results: ' + data.data.median.firstView.loadTime);11 });12});13var wpt = require('webpagetest');14var options = { key: 'A.12345678901234567890123456789012' };15var wpt = new WebPageTest('localhost', options);16wpt.runTest('www.google.com', function(err, data) {17 if (err) return console.log(err);18 console.log('Test Results: ' + data.data.userUrl);19 var testId = data.data.testId;20 wpt.getTestResults(testId, function(err, data) {21 if (err) return console.log(err);22 console.log('Test Results: ' + data.data.median.firstView.loadTime);23 });24});25var wpt = require('webpagetest');26var options = { key: 'A.12345678901234567890123456789012' };27var wpt = new WebPageTest('localhost', options);28wpt.runTest('www.google.com', function(err, data) {29 if (err) return console.log(err);30 console.log('Test Results: ' + data.data.userUrl);31 var testId = data.data.testId;32 wpt.getTestResults(testId, function(err, data) {33 if (err) return console.log(err);34 console.log('Test Results: ' + data.data.median.firstView.loadTime);35 });36});37var wpt = require('webpagetest');38var options = { key: 'A.12345678901234567890123456789012
Using AI Code Generation
1var wpt = require('./wpt.js');2var wpt = new wpt('your_api_key');3wpt.executorToken(function(data){4 console.log(data);5});6var wpt = function(apiKey){7 this.apiKey = apiKey;8 this.executorToken = function(callback){9 var http = require('http');10 var options = {11 };12 callback = callback || function(){};13 var req = http.request(options, function(res) {14 var output = '';15 res.setEncoding('utf8');16 res.on('data', function (chunk) {17 output += chunk;18 });19 res.on('end', function() {20 var obj = JSON.parse(output);21 callback(obj);22 });23 });24 req.on('error', function(err) {25 });26 req.end();27 };28};29module.exports = wpt;
Using AI Code Generation
1var wpt = require('wpt');2wpt.getTestStatus('testId', function(err, data) {3});4wpt.getTestResults('testId', function(err, data) {5});6wpt.getLocations(function(err, data) {7});8wpt.getTesters(function(err, data) {9});10wpt.getTesters('location', function(err, data) {11});12wpt.getTesters('location', 'connection', function(err, data) {13});14});15});16});17});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!