Best JavaScript code snippet using wpt
shelly.js
Source:shelly.js
1/*2 Shelly - GAE Remote API Shell Interface3 andre.leblanc@webfilings.com4 */5Shelly = (function () {6 var SHA = function (txt) { return new jsSHA(txt, "TEXT").getHash("SHA-256", "HEX"); };7 var _head ="";// "<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css' rel='stylesheet' />";8 var _body = "__BODY__";9 var statusBar = {10 timer: null,11 stash: null,12 FLASH_DURATION: 500,13 initialize: function (el) {14 this.el = el;15 return this;16 },17 clear: function () {18 this.el.html("");19 this.stash = null;20 },21 unstash: function () {22 this.el.html(this.stash || "");23 this.stash = null;24 },25 flash: function (message) {26 this.setMessage(message, this.FLASH_DURATION);27 },28 setMessage: function(message, duration) {29 if (this.timer) {30 clearTimeout(this.timer);31 this.timer = null;32 }33 if (!duration) {34 this.stash = null;35 this.el.html(message);36 return;37 } else {38 this.stash = this.el.html();39 this.el.html(message);40 this.timer = setTimeout($.proxy(this.unstash, this), duration);41 }42 }43 };44 Script = function(name, contents, createdAt, modifiedAt) {45 this.name = name;46 this.createdAt = createdAt || new Date();47 this.modifiedAt = modifiedAt || new Date();48 this.contents = contents || "";49 this.computeHash();50 };51 Script.prototype.computeHash = function () {52 this.hash = SHA(this.contents);53 return this.hash;54 }55 var shelly = {56 initialize: function (document) {57 var self = this;58 this.sessionId = $("input[name='session']").val();59 if (!this.sessionId) {60 return;61 }62 $("head script", document).remove();63 $("body", document).empty().append(_body);64 setTimeout(function () {65 // set up the editor and resize events66 var $leftPane = $(".left-pane");67 self.editor = CodeMirror($leftPane.get(0), {68 mode: 'python',69 lineNumbers: true,70 lineWrapping: true,71 viewportMargin: Infinity72 });73 self.editor.on('change', $.proxy(self.onEditorChange, self));74 $(window).on('keypress', function (ke) {75 if (ke.keyCode == 13 && (ke.ctrlKey || ke.metaKey)) {76 self.executeEditorContents();77 }78 });79 $("#run-button").on('click', $.proxy(self.executeEditorContents, self));80 $(window).on('resize', $.proxy(self.onResize, self));81 self.onResize();82 // setup the output 'console'83 self.output = $("div.right-pane");84 $("i.clear-console-button").on('click', $.proxy(self.clearConsole, self));85 self.output.on('click', function (e) {86 if ($(e.target).hasClass('pyprompt')) {87 if (self.promptMenu) {88 self.promptMenu.remove();89 }90 self.createPromptMenu($(e.target));91 e.stopPropagation();92 }93 });94 $(document).on('click', function (e) {95 if (self.promptMenu) {96 self.promptMenu.remove();97 self.promptMenu = null;98 }99 });100 // setup storage101 chrome.storage.local.get("editor_contents", function (data) {102 if (data.editor_contents) {103 self.editor.setValue(data.editor_contents);104 }105 });106 // setup resizer107 self.slider = $("div.slider");108 self.sliding;109 self.slider.on("mousedown", function (e) {110 self.sliding = true;111 $(document).css("-webkit-user-select", "none");112 $(document).one("mouseup", function (e) {113 $(document).css("-webkit-user-select", "text");114 self.sliding = false;115 });116 });117 $(document).on("mousemove", function (e) {118 if (self.sliding) {119 console.log("SliderEvent", e);120 $leftPane.width(e.pageX-5);121 $leftPane.trigger('resize');122 }123 });124 // setup status bar125 self.statusBar = statusBar.initialize($("div.footer"));126 // setup toolbar127 var toolbar = $("div.toolbar");128 $("i,div", toolbar).on('mouseenter', function () {129 statusBar.setMessage($(this).attr("title"));130 }).on('mouseleave', function () {131 statusBar.setMessage("");132 });133 $("#open-dialog-button").on('click', $.proxy(self.openDialog, self));134 $("#save-button").on('click', $.proxy(self.onSaveButton, self));135 $("#save-as-button").on('click', $.proxy(self.onSaveAsButton, self));136 self.loadedScript = new Script("untitled", 'print "Hello World!"\n');137 self.loadedScript.makeNameUnique(function (name) {138 self.editor.setValue(self.loadedScript.contents);139 self.updateSaveStatus();140 self.editor.focus();141 self.statusBar.setMessage("");142 });143 }, 1);144 },145 createPromptMenu: function (promptTag) {146 var self = this;147 self.promptMenu = $("<ul class='menu'><li id='menu-reexec'>Re-execute</li><li id='menu-edit'>Edit</li></ul>");148 self.promptMenu.insertBefore(promptTag).css({top: '5px', left: '5px'});149 $("li", self.promptMenu).on("click", function () {150 var match = $(this).attr("id").match(/^menu\-(.*)$/);151 var pre = $(this).closest("pre.shell-input");152 if (match && match[1] == 'reexec') {153 self.execute(pre.data("scriptBody"));154 } else if (match && match[1] == 'edit') {155 self.editor.setValue(pre.data("scriptBody"));156 }157 self.promptMenu.remove();158 self.promptMenu = null;159 });160 },161 escapeHTML: function (html) {162 var entityMap = {163 "&": "&",164 "<": "<",165 ">": ">",166 '"': '"',167 "'": ''',168 "/": '/'169 };170 return String(html).replace(/[&<>"'\/]/g, function (s) {171 return entityMap[s];172 });173 },174 executeEditorContents: function () {175 this.execute(this.getEditorContents());176 },177 execute: function (script) {178 this.printInput(script);179 $.post("shell.do", {statement: script, session: this.sessionId}, $.proxy(this.printOutput, this));180 },181 onStorageChange: function (changes, areaName) {182 console.log("Storagechanged", areaName, changes);183 },184 openDialog: function() {185 var self = this;186 this.dialog = $(".dialog").modal({onShow: function(dialog) {187 self.onDialogOpened(dialog);188 }});189 },190 onEditorChange: function () {191 if (this.checkTimer !== undefined) {192 clearTimeout(this.checkTimer);193 }194 var self = this;195 setTimeout(function() { self.updateSaveStatus(); }, 500);196 },197 closeDialog: function () {198 this.dialog.close();199 },200 onDialogOpened: function(dialog) {201 var self = this;202 self.refreshDialog();203 dialog.container.drags({handle:".modal-header"});204 $("select.saved-scripts", dialog.container).off('change').on('change', function () {205 if ($(this).val()) {206 $("#open-button").removeClass("disabled");207 $("#delete-button").removeClass("disabled");208 } else {209 $("#open-button").addClass("disabled");210 $("#delete-button").addClass("disabled");211 }212 });213 $("#open-button", dialog.container).on('click', function () {214 if (!$(this).hasClass('disabled')) {215 self.loadScript($("select.saved-scripts").val());216 self.dialog.close();217 }218 });219 $("#delete-button", dialog.container).on('click', function () {220 if (!$(this).hasClass('disabled')) {221 var scriptName = $("select.saved-scripts").val();222 if (confirm("Are you sure you want to delete " + scriptName)) {223 self.deleteScript(scriptName);224 self.refreshDialog();225 }226 }227 });228 $("#cancel-button", dialog.container).off('click').on('click', function () {229 self.closeDialog();230 });231 },232 refreshDialog: function () {233 $("select.saved-scripts").empty();234 chrome.storage.local.get(null, function (data) {235 for (script in data) {236 if (script.substring(0,10) == '__script__') {237 $("select.saved-scripts").append("<option>" + script.substring(10) + "</option>");238 }239 }240 });241 $("#open-button,#delete-button").addClass("disabled");242 },243 updateSaveStatus: function() {244 $("div#save-as-button").html(this.loadedScript.name);245 var dirty = true;246 if (this.loadedScript.hash == SHA(this.editor.getValue())) {247 $("i#save-button").removeClass("fa-floppy-o").addClass("fa-file");248 dirty = false;249 } else {250 $("i#save-button").removeClass("fa-file").addClass("fa-floppy-o");251 }252 chrome.storage.local.set({'editor_contents': this.editor.getValue()});253 },254 onSaveButton: function () {255 if (!this.loadedScript.saved) {256 this.onSaveAsButton();257 return;258 }259 this.loadedScript.contents = this.editor.getValue();260 this.loadedScript.computeHash();261 this.loadedScript.modifiedAt = new Date();262 var save = {};263 save['__script__' + this.loadedScript.name] = this.loadedScript;264 this.updateSaveStatus();265 chrome.storage.local.set(save, function () {266 console.log("Saved ", save);267 });268 },269 onSaveAsButton: function () {270 var name = prompt("Save script as...", this.loadedScript.name);271 if (!name) {272 return;273 }274 this.loadedScript.name = name;275 this.loadedScript.saved = true;276 this.onSaveButton();277 },278 deleteScript: function (scriptName) {279 if (this.loadedScript.name == scriptName) {280 this.loadedScript.hash = "";281 this.updateSaveStatus();282 }283 chrome.storage.local.remove("__script__" + this.loadedScript.name);284 },285 loadScript: function (scriptName) {286 var self = this;287 chrome.storage.local.get("__script__" + scriptName, function (data) {288 self.loadedScript = $.extend(new Script(), data["__script__" + scriptName]);289 console.log(self.loadedScript.contents);290 self.editor.setValue(self.loadedScript.contents);291 self.updateSaveStatus();292 });293 },294 onResize: function (event) {295 var $leftPane = $(".left-pane");296 this.editor.setSize($leftPane.width()-2, $leftPane.height()-32);297 },298 getEditorContents: function () {299 var contents = this.editor.getValue();300 var trimmed = contents.replace(/\n*$/, '');301 return trimmed;302 },303 clearConsole: function() {304 $(".right-pane pre").remove();305 },306 scrollConsole: function () {307 this.output.get(0).scrollTop = this.output.get(0).scrollHeight;308 },309 printInput: function (input) {310 var el = $("<pre class='shell-input'></pre>");311 var scriptBody = input.replace(/\n*$/, '');312 var lines = scriptBody.split("\n");313 var prefix;314 for (var i=0; i<lines.length; i++) {315 if (i == 0) {316 el.append("<strong class='pyprompt'>>>></strong> " + this.escapeHTML(lines[i]) + "\n");317 } else {318 el.append("<strong>...</strong> " + this.escapeHTML(lines[i]) + "\n");319 }320 }321 this.output.append(el);322 el.data('scriptBody', scriptBody);323 this.scrollConsole();324 },325 printOutput: function (output) {326 var el = $("<pre class='shell-output'></pre>");327 el.html(this.escapeHTML(output+"\n"));328 this.output.append(el);329 el.on("dblclick", function (e) {330 var sel = window.getSelection();331 sel.setBaseAndExtent(this, 0, this, 1);332 });333 this.scrollConsole();334 }335 };336 Script.prototype.makeNameUnique = function (callback) {337 var self = this;338 chrome.storage.local.get(null, function (data) {339 var tmpName = self.name;340 var i = 1;341 while (tmpName in data) {342 tmpName = self.name + "-" + num;343 }344 self.name = tmpName;345 callback(self.name);346 });347 }348 return shelly;349})();350$(document).ready(function () {351 Shelly.initialize(document);...
ProfileRunner.ts
Source:ProfileRunner.ts
1import { ILogger } from '../script/loggers';2import { ICancellationToken, CancellationToken } from '../util/CancellationToken';3import { ModuleLoader } from '../script/ModuleLoader';4import { SessionEvents } from './SessionEvents';5import { ISessionOutput } from './ISessionOutput';6import { } from '../script/IScriptDefinition';7import { Script, IScript, IScriptDefinition } from '../script/Script';8import { IProfile } from './Profile';9import * as _ from 'underscore';10import * as fs from '../util/asyncFs';11import * as path from 'path';12import * as Queue from 'promise-queue';13import { FilterRunner } from './filters';14export class ProfileRunner {15 private sessionEvents: ISessionOutput;16 private context: any;17 private files: string[];18 private passedScripts: LoadedScript[] = [];19 private failedScripts: LoadedScript[] = [];20 private filterRunner: FilterRunner;21 constructor(private profile: IProfile, sessionOutput: ISessionOutput) {22 this.sessionEvents = new SessionEvents(sessionOutput);23 this.filterRunner = new FilterRunner()24 }25 async run(cancellationToken?: ICancellationToken): Promise<any> {26 if (cancellationToken == null) cancellationToken = CancellationToken.None;27 this.loadGlobalModules();28 this.registerFilters();29 try {30 if (!await this.filterRunner.onSessionStarting()) {31 return;32 }33 this.sessionEvents.onSessionStarted()34 await Promise.all([35 this.buildContext(),36 this.buildFileList()37 ]);38 await this.runFiles(cancellationToken);39 this.sessionEvents.onSessionFinished(this.passedScripts.length, this.failedScripts.length);40 }41 finally {42 await this.filterRunner.onSessionFinished(this.passedScripts.length, this.failedScripts.length);43 }44 }45 private loadGlobalModules() {46 if (this.profile.modules == null) return;47 for (let i = 0; i < this.profile.modules.length; i++) {48 require(this.profile.modules[i].path);49 }50 }51 private registerFilters() {52 if (this.profile.filters == null) return;53 for (let i = 0; i < this.profile.filters.length; i++) {54 require(this.profile.filters[i]);55 }56 }57 private async buildContext(): Promise<any> {58 this.context = {};59 const contexts = this.profile.contexts;60 if (contexts == null ||61 contexts.length == 0) {62 return;63 }64 for (let i = 0; i < contexts.length; i++) {65 const path = contexts[i];66 const context = await this.readContextFile(path);67 _.extend(this.context, context);68 }69 }70 private async readContextFile(filePath: string): Promise<any> {71 if (_.isObject(filePath)) return filePath;72 const isJson = filePath.endsWith('.json');73 const isYaml = filePath.endsWith('.yml') || filePath.endsWith('.yaml');74 if (!isJson && !isYaml) throw new Error('Context file must be .json or .yaml');75 let readFunc = isJson ? fs.readAsJson : fs.readAsYaml;76 const fullPath = path.resolve(filePath);77 let stat;78 try {79 stat = await fs.stat(fullPath);80 }81 catch (err) {82 throw new Error(`Context file "${filePath}" does not exist`);83 }84 return await readFunc(fullPath);85 }86 private async buildFileList() {87 const fileNames = _.uniq(_.flatten(await Promise.all(_.map(this.profile.include, (include) => this.listFilesForPath(include)))));88 this.files = _.filter(fileNames, (name) => name.toLowerCase().endsWith('.puml'));89 }90 private async listFilesForPath(filePath: string): Promise<string[]> {91 const fullPath = path.resolve('.', filePath);92 let stat;93 try {94 stat = await fs.stat(fullPath);95 }96 catch (err) {97 throw new Error(`"${filePath}" is not a file or directory`);98 }99 if (stat.isFile()) {100 return [fullPath];101 }102 if (stat.isDirectory()) {103 const dirFiles = await fs.readdir(fullPath, this.profile.isRecursive);104 return _.map(dirFiles, f => path.resolve(fullPath, f));105 }106 throw new Error(`"${filePath}" is not a file or directory`);107 }108 private async runFiles(cancellationToken: ICancellationToken): Promise<any> {109 const queue = new Queue(this.getMaxConcurrentFiles(), Infinity);110 await Promise.all(_.map(this.files, (file) => queue.add(() => this.runFile(file, cancellationToken))));111 }112 private async runFile(filename: string, cancellationToken: ICancellationToken): Promise<any> {113 if (cancellationToken.isCancellationRequested) return;114 let scriptDetails: LoadedScript;115 try {116 scriptDetails = await LoadedScript.load(filename, this.sessionEvents);117 }118 catch (e) {119 e.message = `Error parsing file ${filename}: ${e.message}`;120 throw e;121 }122 this.sessionEvents.onScriptPending(scriptDetails.script.id, filename, scriptDetails.script.name);123 await this.runScript(scriptDetails, cancellationToken);124 }125 private async runScript(scriptContainer: LoadedScript, cancellationToken: ICancellationToken): Promise<any> {126 if (cancellationToken.isCancellationRequested) return;127 if (!await this.filterRunner.onScriptStarting(scriptContainer.script)) {128 return;129 }130 this.sessionEvents.onScriptStarted(scriptContainer.script.id);131 await this.loadModules(scriptContainer);132 this.context.__filename = scriptContainer.fileName;133 try {134 await scriptContainer.script.run(this.context, cancellationToken);135 this.passedScripts.push(scriptContainer);136 this.sessionEvents.onScriptFinished(scriptContainer.script.id, null);137 this.filterRunner.onScriptFinished(scriptContainer.script, true);138 }139 catch (err) {140 this.failedScripts.push(scriptContainer);141 this.sessionEvents.onScriptFinished(scriptContainer.script.id, err);142 this.filterRunner.onScriptFinished(scriptContainer.script, false);143 }144 }145 private async loadModules(s: LoadedScript): Promise<any> {146 const modules = this.profile.modules;147 if (modules != null) {148 for (let i = 0; i < modules.length; i++) {149 s.script.addModule(modules[i].name);150 }151 }152 ModuleLoader.load(s.fileName, s.scriptDefinition.modules);153 }154 private DEFAULT_QUEUE_SIZE = 15;155 private getMaxConcurrentFiles(): number {156 return this.profile.maxConcurrentFiles != null 157 ? this.profile.maxConcurrentFiles158 : this.DEFAULT_QUEUE_SIZE;159 }160}161class LoadedScript {162 script: IScript;163 constructor(public scriptDefinition: IScriptDefinition, public fileName: string, emitter: ISessionOutput) {164 const emittingLogger: ILogger = {165 debug: (msg) => { emitter.onLog(this.script.id, 'debug', msg); },166 log: (msg) => { emitter.onLog(this.script.id, 'log', msg); },167 warn: (msg) => { emitter.onLog(this.script.id, 'warn', msg); },168 error: (msg) => { emitter.onLog(this.script.id, 'error', msg); }169 }170 this.script = new Script(scriptDefinition, { logger: emittingLogger });171 }172 static async load(filename: string, emitter: ISessionOutput): Promise<LoadedScript> {173 const scriptDefinition = <IScriptDefinition> await fs.readAsYaml(filename);174 return new LoadedScript(scriptDefinition, filename, emitter);175 }...
long-script-content.js
Source:long-script-content.js
1// Copyright 2017 The Chromium Authors. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be3// found in the LICENSE file.4(async function() {5 TestRunner.addResult(`Tests long script content is correctly shown in source panel after page reload.\n`);6 await TestRunner.loadModule('network_test_runner');7 await TestRunner.loadModule('sources_test_runner');8 await TestRunner.loadModule('console_test_runner');9 await TestRunner.showPanel('sources');10 await TestRunner.showPanel('network');11 await TestRunner.navigatePromise('resources/long-script-page.html');12 TestRunner.hardReloadPage(step1);13 function step1() {14 ConsoleTestRunner.addConsoleSniffer(step2);15 TestRunner.evaluateInPage('loadScript()');16 }17 function step2(event) {18 TestRunner.evaluateInPage('unloadScript()', step3);19 }20 function step3() {21 SourcesTestRunner.waitForScriptSource('long_script.cgi', step4);22 }23 function step4(uiSourceCode) {24 TestRunner.evaluateInPage('gc()', step5.bind(null, uiSourceCode));25 }26 function step5(uiSourceCode) {27 uiSourceCode.requestContent().then(step6);28 }29 function step6(loadedScript) {30 var expected = 'console.log(\'finished\');\n';31 TestRunner.assertTrue(!!loadedScript, 'No script content');32 loadedScript = loadedScript.replace(/\r\n/g, '\n'); // on windows we receive additional symbol \r at line end.33 TestRunner.assertEquals(1024 * 10240 + expected.length, loadedScript.length, 'Loaded script length mismatch');34 var actual = loadedScript.substring(loadedScript.length - expected.length);35 TestRunner.assertEquals(expected, actual, 'Loaded script is corrupted');36 TestRunner.addResult('Test passed');37 TestRunner.completeTest();38 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var options = {4};5 if (err) return console.error(err);6 console.log('Test submitted to WebPageTest! Check back here for results: ' + data.data.userUrl);7 console.log('Test ID: ' + data.data.testId);8 wpt.getTestResults(data.data.testId, function(err, data) {9 if (err) return console.error(err);10 console.log('First View Speed Index: ' + data.data.average.firstView.SpeedIndex);11 console.log('Repeat View Speed Index: ' + data.data.average.repeatView.SpeedIndex);12 });13});
Using AI Code Generation
1var wpt = require('webpagetest')(wptServer, wptKey);2wpt.runTest(url, function(err, data) {3 if (err) {4 console.log(err);5 } else {6 wpt.getTestResults(data.data.testId, function(err, data) {7 if (err) {8 console.log(err);9 } else {10 console.log(data.data.average.firstView.SpeedIndex);11 }12 });13 }14});
Using AI Code Generation
1var wpt = require('wpt.js');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.getLocations(function(data) {4 console.log(data);5});6### getLocations(callback)7### getTesters(callback)8### getTestStatus(testId, callback)9### getTestResults(testId, callback)10### runTest(url, options, callback)11### runTest(url, callback)12### runTest(url, options)13### runTest(url)14wpt.getLocations(function(data) {15 console.log(data);16});17wpt.getTesters(function(data) {18 console.log(data);19});20wpt.getTestStatus('120522_4T_1e0a', function(data) {21 console.log(data);22});23wpt.getTestResults('120522_4T_1e0a', function(data) {24 console.log(data);25});26}, function(data) {27 console.log(data);28});
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var wpt = new WebPageTest('www.webpagetest.org', 'A.9d5c5b5e5d5c5b5e5d5c5b5e5d5c5b5e');5var params = {6};7wpt.runTest(url, params, function(err, data) {8 if (err) return console.error(err);9 console.log('Test submitted to WebPageTest for %s', url);10 console.log('View your test at: %s', data.data.userUrl);11 wpt.getTestResults(data.data.testId, function(err, data) {12 if (err) return console.error(err);13 console.log('Test completed for %s', url);14 console.log('View your test at: %s', data.data.userUrl);15 });16});
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!!