Best JavaScript code snippet using puppeteer
require5.js
Source:require5.js
1/**2 Require5.JS just like NodeJS style require function for the browser3 (c) DazaGrohovaz.Net guidoalfredo@dazagrohovaz.net / ProxyJS.com support@proxyjs.com4 Features:5 - load, compile and run scripts once6 - support sync and async XHR requests7 - storage the scripts on HTML5 Storage if available8 - data transfer only if required, load scripts from storage or cache9 if available (no transfer), otherwise load scripts via XHR (data transfer)10 - cross-domain requests (no support data storage)11 12 dependencies:13 utils/ajax.js14 utils/path.js15 Permission is hereby granted, free of charge, to any person obtaining16 a copy of this software and associated documentation files (the17 "Software"), to deal in the Software without restriction, including18 without limitation the rights to use, copy, modify, merge, publish,19 distribute, sublicense, and/or sell copies of the Software, and to20 permit persons to whom the Software is furnished to do so, subject to21 the following conditions:22 The above copyright notice and this permission notice shall be23 included in all copies or substantial portions of the Software.24 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,25 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF26 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND27 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE28 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION29 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION30 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.31*/32if(!global) var global = window.global = window;33// For development, IMPORTANT..!!! Ignore the cache and storage34if(true /** development??? Set this to true */){35 if(!global.runUnitTest) global.runUnitTest = {}; 36 global.runUnitTest.require = true;37 global.runUnitTest.resolveUri = false;38}39/**40 utils/ajax.js41 (c) DazaGrohovaz.Net <dazagrohovaz.net>42*/43(function(){44 // Ajax / XHR45 xhr = this.xhr = function(){46 var xhr = null;47 try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }48 catch(e){49 try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }50 catch(e){ xhr = null; }51 }52 if(!xhr && typeof XMLHttpRequest != "undefined") xhr = new XMLHttpRequest();53 return xhr;54 }55}).call(global);56/**57 utils/path.js58 (c) DazaGrohovaz.Net <dazagrohovaz.net>59*/60(function(){61 var62 // save global in closure63 global = this,64 65 // parseUri 1.2.266 // (c) Steven Levithan <stevenlevithan.com>67 // MIT License68 // MOD: (c) DazaGrohovaz.Net <dazagrohovaz.net>69 parseUri = this.parseUri = function(path){70 var o = parseUri.options,71 // MOD: normalize path72 m = o.parser[o.strictMode ? "strict" : "loose"].exec(normalizeUri(path)),73 // m = o.parser[o.strictMode ? "strict" : "loose"].exec(path),74 uri = {},75 i = 14;76 77 while (i--) uri[o.key[i]] = m[i] || '';78 79 uri[o.q.name] = {};80 uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {81 if ($1) uri[o.q.name][$1] = $2;82 });83 84 // MOD:85 // normalized property86 uri.normalized = uri.source;87 uri.source = path;88 89 // MOD:90 // toString, toSource functions91 var url = uri.normalized;92 uri.toString = function(){93 return url;94 };95 var source = uri.source;96 uri.toSource = function(){97 return source;98 };99 100 return uri;101 };102 103 parseUri.options = {104 strictMode: false,105 key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],106 q: {107 name: "queryKey",108 parser: /(?:^|&)([^&=]*)=?([^&]*)/g109 },110 parser: {111 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,112 loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/113 }114 };115 116 // normalizeUri 0.0.1117 // (c) DazaGrohovaz.Net <dazagrohovaz.net>118 normalizeUri = this.normalizeUri = function(path){119 var url = path + ((path.substr(-1)=='.') ? '/' : '');120 121 url = url.replace('/.?', '/./?');122 url = url.replace('/..?', '/../?');123 var slashLocation = url.indexOf("/"); // temp variable to store location of slashmark124 var previousIndex = 0; // temp variable to store location of previous slashmark125 var nextPreviousIndex = 0; // temp variable to store location of next previous slashmark126 127 if (slashLocation > -1) { // check if url has any slashes in it128 129 while (slashLocation < url.length) { // while conditional to iterate from start to finish through all slashes in the url string130 131 if (url.charAt(slashLocation-1)==".") {132 133 if ((url.charAt(slashLocation-2)==".")&&(url.charAt(slashLocation-3)=="~")) { // if two periods before the slash, remove all characters between next previous slash and current slash134 135 var oldLength = url.length;136 var offset = 0;137 138 url = url.substr(0,nextPreviousIndex)+"~"+url.substr(slashLocation+1,url.length-slashLocation-1);139 offset = oldLength-url.length;140 141 var tempurl = url.substr(0,nextPreviousIndex);142 nextPreviousIndex = tempurl.lastIndexOf("~");143 previousIndex = slashLocation - offset;144 145 oldLength = null;146 tempurl = null;147 offset = null;148 149 } else if (url.charAt(slashLocation-2)=="~") { // if only one period before the slash, remove "./"150 151 url = url.substr(0,slashLocation-2)+"~"+url.substr(slashLocation+1,url.length-slashLocation);152 153 var tempurl = url.substr(0,previousIndex);154 nextPreviousIndex = tempurl.lastIndexOf("~");155 tempurl = null;156 157 previousIndex = slashLocation-2;158 159 } else {160 161 url = url.substr(0,slashLocation) + "~" + url.substr(slashLocation+1,url.length-slashLocation);162 nextPreviousIndex = previousIndex;163 previousIndex = slashLocation; 164 165 }166 } else if (url.charAt(slashLocation-1)=="~") { // if have slash mark before the slash, remove one167 168 url = url.substr(0,slashLocation) + url.substr(slashLocation+1,url.length-slashLocation);169 170 var tempurl = url.substr(0,previousIndex);171 nextPreviousIndex = tempurl.lastIndexOf("~");172 tempurl = null;173 174 previousIndex = slashLocation-1;175 176 } else { // otherwise just replace the slash with a random character, a tilda, to keep iterating through the url in the while loop177 url = url.substr(0,slashLocation) + "~" + url.substr(slashLocation+1,url.length-slashLocation);178 nextPreviousIndex = previousIndex;179 previousIndex = slashLocation;180 181 }182 183 slashLocation = url.indexOf("/"); // this iterates to the next slash in the url string184 if (slashLocation == -1) break; // if can't find any more slashes in the url string, then stop iterating185 186 } 187 }188 189 // clear out temp variables to avoid memory leaks190 slashLocation = null;191 previousIndex = null;192 nextPreviousIndex = null;193 194 url = url.replace(/~/g,"/"); // return the url after replacing the inserted tildas with slashes195 196 url = ( url.substr(0,5) == 'http:' ) ? url.replace('http:', 'http:/') : url;197 url = ( url.substr(0,6) == 'https:' ) ? url.replace('http:', 'https:/') : url;198 199 return url;200 }201 202 // resolveUri 0.0.1203 // (c) DazaGrohovaz.Net <dazagrohovaz.net>204 resolveUri = this.resolveUri = function(basePath, path){205 // handle nulls206 if(!basePath){207 try {208 basePath = window.location.href;209 }catch(e){210 basePath = __dirname;211 }212 }213 if(!path)path='';214 215 // parse basePath216 var baseUri = parseUri(basePath);217 baseUri = parseUri(218 baseUri.protocol + (!!baseUri.protocol ? '://' : '') + 219 baseUri.authority + 220 baseUri.directory + 221 ((baseUri.directory.substr(-1) != '/') ? '/../' : ''));222 223 // parse path224 var uri = parseUri((225 (!path || path.substr(0,2) == '/.' || path.substr(0,3) == '/..' || !(path.substr(0,5) == 'http:' || path.substr(0,6) == 'https:'))226 ? ((path.substr(0,1) == '/')227 ? baseUri.protocol + (!!baseUri.protocol ? '://' : '') + baseUri.authority : baseUri )228 : '' )229 + path );230 231 if(global.runUnitTest && global.runUnitTest.resolveUri)232 console.log('\nbasePath : ' + basePath + 233 '\npath : ' + path + 234 '\nbaseUri : ' + baseUri + 235 '\nuri : ' + uri + 236 '\nsource : ' + uri.toSource());237 238 return uri;239 };240}).call(global);241/**242 require5.js 243 (c) DazaGrohovaz.Net <dazagrohovaz.net>244*/245(function(){246 var247 // main path248 __root = normalizeUri(resolveUri().normalized+'/require5.js'), 249 250 // implements HTML5 Storage Support if available251 storage = (function() {252 try {253 return ('localStorage' in window && window['localStorage'] !== null) ? window['localStorage'] : undefined;254 } catch (e) {255 return undefined;256 }257 })(),258 259 // m:260 // memory cache261 // look at the comments to see the differences between NodeJS require function and Require5.JS262 m = {263 // paths: list of all required or defined (unshift) javascript files.264 // it's an Object because it noted whether the package status is.265 // {'http://www.example.com/lib/scripts/require5.js': 'unshift' || 'fails' || 'ready'}266 paths: {},267 268 // alias (new): used to implement browser optimized unshift method. example:269 // if the browser href is 'http://www.example.com/somepath/somepage.html'270 // or the unshift-method is called from 'http://www.example.com/somepath/somescript.js'271 // like require.paths.unshift('path/to/my/file.js', 'myscript')272 // first resolve the path ('http://www.example.com/somepath/path/to/my/file.js')273 // then set alias['myscript'] = 'http://www.example.com/somepath/path/to/my/file.js';274 // if the path don't exixts on paths275 // then set paths['http://www.example.com/somepath/path/to/my/file.js'] = 'unshift';276 // now it's posible to call require('myscript');277 // it will reffer to 'http://www.example.com/somepath/path/to/my/file.js'278 alias: {},279 280 // cache: collection of all instances of loaded packages, fails too (for debug reasons)281 cache: {},282 283 // implements HTML5 Storage Support if available284 useStorage: !(global.runUnitTest && global.runUnitTest.require) && storage, 285 },286 // END m:287 288 // require: prepare require capabilities on 'this' context289 require = function(request){290 var291 // __resolveUri:292 // resolve relation between 2 paths, from basePath(__dirname) and request(__filename)293 // accepts querystring(?) and dependencies(#), just like in brower294 __resolveUri = function(basePath, request){295 var296 297 // resolve Uri or Path298 res = resolveUri(basePath, request),299 300 // extend resolveUri for require:301 // check file extention (only '.js' files allow)302 // if not match append '/index.js' to the Url303 url = res.protocol + (!!res.protocol ? '://' : '') + res.authority + 304 res.directory + ((res.directory.substr(-1) != '/' ) ? '/' : '') + 305 res.file + ((!!res.file && res.file.substr(-3) == '.js' ) ? '' : '/index.js')306 307 // no querystring and anchor308 //( !!res.query ? '?' : '' ) + res.query + 309 //( !!res.anchor ? '#' : '' ) + res.anchor;310 311 // normalize the url and return it312 return normalizeUri(url);313 },314 // END resolve:315 316 // __require:317 __require = function(request){318 if(!request || typeof request !== 'string' ) return null;319 if(!(this instanceof __require)) return new __require(request);320 321 var 322 323 // set __self as the module324 __self = this,325 326 // parse the request327 uri = parseUri(request),328 329 // look if main/root module was defiened 330 __main = ( !!m.paths[0] ? m.cache[m.paths[0]].module : undefined ),331 332 // path and querystring333 __module = __self.__module = uri.protocol + (!!uri.protocol ? '://' : '') + uri.authority + 334 uri.directory + ((uri.directory.substr(-1) != '/' ) ? '/' : '') + 335 uri.file + ((!!uri.file && uri.file.substr(-3) == '.js' ) ? '' : '/index.js'),336 337 __query = __self.__query = uri.query,338 339 // querystring as object340 __query = __self.__query = uri.queryKey,341 342 // directory and file names343 __dirname = __self.__dirname = __module.slice(0, __module.length - uri.file.length),344 __filename = __self.__filename = uri.file,345 346 // anchor347 __anchor = __self.__anchor = ( !!uri.anchor ? uri.anchor : '' ),348 349 // require350 require = __self.require = function(path, callback){ return _require(path, callback); },351 352 // resolve353 resolve = __self.resolve = function(request){ return _resolve(request); },354 355 // memory cache356 useStorage = __self.useStorage = m.useStorage,357 alias = __self.alias = m.alias,358 cache = __self.cache = m.cache,359 paths = __self.paths = m.paths,360 361 // context362 context = __self.context = {},363 364 // unshift with require and callback365 unshift = paths.unshift = function(unshift, path){366 // perform alias (new): used to implement browser optimized unshift method. example:367 // if the browser href is 'http://www.example.com/somepath/somepage.html'368 // or the unshift-method is called from 'http://www.example.com/somepath/somescript.js'369 // like require.paths.unshift('path/to/my/file.js', 'myscript')370 if(!unshift || typeof unshift !== 'string') return undefined;371 if(!path || typeof path !== 'string') return undefined;372 373 // first resolve the path ('http://www.example.com/somepath/path/to/my/file.js')374 var request = __resolveUri(__dirname, path)375 376 // then set alias['myscript'] = 'http://www.example.com/somepath/path/to/my/file.js';377 alias[unshift] = request;378 379 // if the path don't exixts on paths380 // then set paths['http://www.example.com/somepath/path/to/my/file.js'] = 'unshift';381 paths[request] = paths[request] || 'unshift';382 383 // now it's posible to call require('myscript');384 // it will reffer to 'http://www.example.com/somepath/path/to/my/file.js'385 386 // return the request path if it done387 return request;388 },389 // END unshift390 391 // module392 module = __self.module = {393 id : __filename,394 exports : {},395 filename : __module,396 loaded : 0,397 error : undefined,398 cached : false,399 parent : undefined,400 paths : paths401 },402 // END module403 404 // main405 main = __self.main = __main,406 407 // exports408 exports = __self.exports = function(){ return __self.module.exports; },409 410 // _resolve411 _resolve = __self._resolve = function(request){412 var apath = alias[request],413 path = apath || __resolveUri(__dirname, request),414 status = paths[path];415 416 // _resolve: resolve paths of all required or defined (unshift) javascript files.417 // it return a object because it noted whether the package alias, path and status is.418 // { alias: 'myscript', path: 'http://www.example.com/require5.js', status: 'unshift' || 'loaded' || 'fails' || 'ready' || undefined }419 return { alias: ( !!apath ? request : undefined ), path: path, status: status, };420 },421 // END _resolve422 423 // _require:424 // load the required modules, extention '.js' require !!!425 // the path muss be like 'file.js', otherweise require will search 'index.js'426 // it is in this case not like NodeJS, but most appropriate for the browser427 _require = __self._require = function(request, callback){428 429 // resolce request430 var info = _resolve(request),431 432 // if callback is passed run async433 async = (!!callback && typeof callback === 'function'),434 435 // parse436 // run script parse at response and analize the result437 parse = function(response){438 var 439 440 // make new module441 Module = new __require(info.path),442 443 // execute the script444 result = exec.call(Module, response);445 446 // validate the result447 if( Module !== result ){448 // append error object to exports, remove from storage and set status to 'fails'449 Module.module.exports.error = Module.module.error = result;450 if( useStorage ) storage.removeItem('script.' + info.path);451 paths[info.path] = 'fails';452 } else {453 // save the script into storage, set status to ready, increment loaded-counter454 if( useStorage ) storage.setItem('script.' + info.path, response);455 paths[info.path] = 'ready';456 Module.module.loaded++;457 Module.ready = true;458 459 // save module into the cache460 cache[info.path] = Module;461 Module.module.cached = true;462 } 463 464 // extend module.parent465 Module.module.parent = function(){ return __self.module };466 467 // wait 1ms to execute callback to ensure that require return the getContext function468 if(async){469 setTimeout(function(){470 callback.call( window, Module.module.exports, Module.module, Module.require, Module.__dirname, Module.__filename );471 },1);472 }473 // if no async return exports474 if(!async) return Module.module.exports;475 },476 // END parse477 478 // fired on Error479 error = function(e){480 console.log("Couldn't resolve path: " +481 "'" + request + "' with respect to filename '" + __module + "': " +482 "file can't resolve past base");483 484 if(e)console.log(e);485 },486 487 // fired on Request Ready or State Change488 onReadyStateChange = function(){489 // readyState == 4 : complete, status == 200 || 304 : success490 if(this.readyState == 4){491 if(this.status == 200 || this.status == 304){492 if( async) return parse(this.responseText);493 }else{494 error(this.status + ': ' + this.statusText + '\n' + 495 '// ===== BEGIN OF FILE ===== //\n\n' +496 this.responseText +497 '\n\n// ===== BEGIN OF FILE ===== //\n/n');498 }499 }500 },501 502 // execute the called module503 exec = function(script){504 // create a new global function505 var scriptString =506 'window[\'script.' + this.__module + '\'] = function(){\n' +507 ' try {\n' +508 ' (function(global, require, module, exports, __dirname, __filename ){\n' + // REMOVED: __module, __query, __queryKey, __anchor509 ' this.global = this;\n' +510 ' "===== BEGIN OF FILE =====";\n' +511 script + '\n' +512 ' "===== END OF FILE =====";\n' +513 ' }).call(window, window, this.require, this.module, this.module.exports, this.__dirname, this.__filename);\n' + // REMOVED: this.__module, this.__query, this.__queryKey, this.__anchor 514 ' return this;\n' +515 ' } catch(e) {\n' +516 ' return { e: e };\n' +517 ' }\n' +518 '}\n';519 520 try{521 // append script into the head (replace the eval function)522 var js = document.createElement('script');523 js.setAttribute('type', 'text/javascript');524 js.text = scriptString;525 document.head.appendChild(js);526 527 // calling the new function528 var result = window['script.' + this.__module].call(this);529 if( result !== this ) result.src = script;530 531 // once compiled remove the script to prevent unwanted calls532 delete window['script.' + this.__module];533 document.head.removeChild(js);534 535 // return result back536 return result;537 } catch(e) {538 return { e: e, src: script };539 }540 };541 542 // resolve Origin to make cross-domain calls543 var host = parseUri(info.path);544 host = host.protocol + (!!host.protocol ? '://' : '') + host.authority + '/'545 546 // if status ready547 if( info.status == 'ready' ){548 // cross-domain549 if(__module.slice(0,host.length) != host){550 if(async){551 // wait 1ms to execute callback to ensure that require return the function552 setTimeout(function(){553 callback.call( window, 'ready' );554 },1);555 }556 return function(){ return { ready: true } };557 } // otherwise558 // search the module in the cache559 var Module = cache[info.path];560 // if the module is present561 if( !!Module ){562 // increment the loaded-counter563 Module.module.loaded++;564 if(async){565 // wait 1ms to execute callback to ensure that require return the getContext function566 setTimeout(function(){567 callback.call( window, Module.module.exports, Module.module, Module.require, Module.__dirname, Module.__filename );568 },1);569 }570 // if no async return exports571 if(!async) return Module.module.exports;572 } else {573 // something is wrong574 error();575 }576 } else {577 // implements HTML5 Storage Support if available578 var script = ( useStorage && info.status != 'fails' ) ? storage.getItem('script.' + info.path) : undefined;579 580 if(!!script){581 // if the script was available in storage parse the script582 if(async) parse(script);583 if(!async) return parse(script);584 } else {585 // cross-domain: appendChild to the head586 if(__module.slice(0,host.length) != host){587 var 588 cross = {},589 js = document.createElement('script');590 paths[info.path] = 'fails';591 592 // onload set paths and module state to ready593 js.onload = function(){594 paths[info.path] = 'ready';595 cross.ready = true;596 document.head.removeChild(js);597 if(async) callback.call( window, 'ready' );598 };599 js.onreadystatechange = function(){600 if(this.readyState=='loaded'){601 paths[info.path] = 'ready';602 cross.ready = true;603 document.head.removeChild(js);604 if(async) callback.call( window, 'ready' );605 }606 };607 608 js.src = info.path;609 // once compiled remove script610 document.head.appendChild(js);611 612 return function(){ return cross };613 } else {614 // otherwise request the script with XHR615 var req = new xhr();616 req.open('GET', info.path, async);617 // for unittest modus set request header If-Modified-Since618 if(global.runUnitTest && global.runUnitTest.require) req.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2005 00:00:00 GMT');619 req.onreadystatechange = onReadyStateChange;620 req.send();621 622 // return exports623 if(!async) return parse(req.responseText);624 }625 }626 }627 // return getContext function, cross-domain calls return allways 628 if(async) return function(){ // getContext-function629 // exports, module, require, __dirname, __filename630 Module.context.ready = Module.ready || false;631 Module.context.exports = Module.module.exports;632 Module.context.module = Module.module;633 Module.context.require = Module.require;634 Module.context.__dirname = Module.__dirname;635 Module.context.__filename = Module__filename;636 637 return Module.context;638 };639 // END if status ready640 };641 // end _require642 643 // extend require644 __self.require.alias = alias;645 //__self.require.cache = cache;646 __self.require.paths = paths;647 __self.require.resolve = resolve;648 649 return __self;650 }651 // END __require652 653 // make the first module 'require5.js'654 Require = new __require( request ),655 656 // set path657 m.paths[request] = 'ready';658 Require.module.loaded++;659 660 // set cache661 m.cache[request] = Require;662 Require.module.cached = true;663 664 // set alias665 m.alias['require']=__root;666 667 // extend module.parent668 Require.module.parent = undefined;669 670 // extends module.exports.global, require & module671 Require.module.exports.global = window;672 Require.module.exports.require = Require.require;673 Require.module.exports.module = Require.module;674 675 // look at storage for saved packages676 if( !!m.useStorage ){677 for(var prop in storage){678 if(prop.slice(0,7)==='script.'){679 var script = prop.slice(7);680 m.paths[script] = 'loaded';681 }682 }683 }684 685 return Require.module.exports;686 }687 // END require: prepare require capabilities on 'this' context688 this.exports = require( __root );689 690 this.global = window;691 this.require = this.exports.require;692 this.module = this.exports.module;693 694 // protect scripts695 Function.prototype.toString = function(){696 return 'function() { [native code] }'697 };698 ...
app.js
Source:app.js
1/**2 * Module dependencies.3 */4var express = require('express')5 , routes = require('./routes')6 , variables = require('./routes/variables')7 , scripts = require('./routes/scripts')8 , folder = require('./routes/folder')9 , script = require('./routes/script')10 , users = require('./routes/users')11 , projects = require('./routes/projects')12 , variableTags = require('./routes/variableTags')13 , userTags = require('./routes/userTags')14 , userStates = require('./routes/userStates')15 , machines = require('./routes/machines')16 , machinetags = require('./routes/machineTags')17 , actions = require('./routes/actions')18 , actiontags = require('./routes/actionTags')19 , machineroles = require('./routes/machineRoles')20 , fileupload = require('./routes/fileupload')21 , common = require('./common')22 , auth = require('./routes/auth')23 , terminal = require('./routes/terminal')24 , realtime = require('./routes/realtime')25 , testsets = require('./routes/testsets')26 , hosts = require('./routes/hosts')27 , templates = require('./routes/templates')28 , uploadFiles = require('./routes/uploadfiles')29 , importtcs = require('./routes/importtcs')30 , rununittest = require('./routes/rununittest')31 , testcases = require('./routes/testcases')32 , testcaseTags = require('./routes/testcaseTags')33 , executions = require('./routes/executions')34 , executionTags = require('./routes/executionTags')35 , executiontestcases = require('./routes/executiontestcases')36 , executionengine = require('./routes/executionengine')37 , screenshots = require('./routes/screenshots')38 , heartbeat = require('./routes/heartbeat')39 , results = require('./routes/results')40 , methodFinder = require('./routes/methodFinder')41 , aggregate = require('./routes/aggregate')42 , executionstatus = require('./routes/executionStatus')43 , emailsettings = require('./routes/emailsettings')44 , imageautomation = require('./routes/imageautomation')45 , recorder = require('./routes/recorder')46 , license = require('./routes/license')47 , almsettings = require('./routes/almsettings')48 , almupload = require('./routes/almupload');49//var app = express.createServer();50process.setMaxListeners(300);51var app = express();52process.env.TMPDIR = __dirname + '/logs';53process.env.TMP = __dirname + '/logs';54process.env.TEMP = __dirname + '/logs';55// Configuration56//app.configure(function(){57 //app.use(express.bodyParser());58 //app.use(express.multipart());59 //app.use(express.bodyParser({ keepExtensions: true, uploadDir: 'c:/temp' }));60 app.use(express.static(__dirname + '/public'));61 //app.use(express.json());62 //app.use(express.urlencoded());63 app.use(express.json({limit: '50mb'}));64 app.use(express.urlencoded({limit: '50mb'}));65 app.use(express.cookieParser());66 app.use(express.methodOverride());67 app.use(app.router);68 //app.use(express.static(__dirname + '/public'));69//});70//app.configure('development', function(){71 app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));72//});73//app.configure('production', function(){74 app.use(express.errorHandler());75//});76//DB77// Routes78app.post('/login',auth.logIn,auth.logInSucess);79app.get('/login',auth.loginPage);80app.post('/license',auth.auth,license.licensePost);81app.get('/license',auth.auth,license.licenseGet);82//emailsettings83app.post('/emailsettings',auth.auth,emailsettings.Post);84app.get('/emailsettings',auth.auth,emailsettings.Get);85//almsettings86app.post('/almsettings',auth.auth,almsettings.Post);87app.get('/almsettings',auth.auth,almsettings.Get);88//almupload89app.post('/almupload',auth.auth,almupload.Post);90//aggregate91app.post('/aggregate',auth.auth,aggregate.aggregatePost);92//imageautomation93app.post('/recordimage',auth.auth,imageautomation.recordImage);94app.get('/image/:id',auth.auth,imageautomation.getImage);95app.post('/recordedimage',imageautomation.recordedImage);96//uploadFiles97app.post('/uploadfiles',auth.auth,uploadFiles.uploadFiles);98app.post('/uploadfromagent',uploadFiles.uploadFromAgent);99app.post('/uploadfilesdone',uploadFiles.uploadDone);100//importAllTCs101app.post('/importalltcs',importtcs.importAllTCs);102app.post('/getallunittcs',importtcs.getAllUnitTests);103app.post('/importselectedtcs',importtcs.importSelectedTCs);104//rununittest105app.post('/rununittest',rununittest.runUnitTest);106app.post('/rununittest/result',rununittest.unitTestResult);107app.post('/rununittest/log',rununittest.unitTestLog);108app.post('/stopunittest',rununittest.stopUnitTest);109//recorder110app.post('/record',auth.auth,recorder.record);111app.post('/record/recorded',recorder.recorded);112//screenshots113app.post('/screenshots',screenshots.Post);114app.get('/screenshots/:id',auth.auth,screenshots.Get);115app.get('/',auth.auth, routes.index);116app.get('/index.html',auth.auth,function(req,res){res.sendfile(__dirname+'/index.html');});117//variables118app.get('/variables', auth.auth, variables.variablesGet);119app.put('/variables/:id',auth.auth, variables.variablesPut);120app.post('/variables',auth.auth, variables.variablesPost);121app.del('/variables/:id',auth.auth, variables.variablesDelete);122//variableTags123app.get('/variableTags',auth.auth, variableTags.variableTagsGet);124app.post('/variableTags',auth.auth, variableTags.variableTagsPost);125//start execution126app.post('/executionengine/startexecution', executionengine.startexecutionPost);127//stop128app.post('/executionengine/stopexecution',auth.auth, executionengine.stopexecutionPost);129app.post('/executionengine/actionresult',executionengine.actionresultPost);130app.post('/executionengine/logmessage',executionengine.logPost);131//heartbeat132app.post('/heartbeat',heartbeat.heartbeatPost);133//results134app.get('/results/:id',results.resultsGet);135app.get('/resultslogs/:id/:executionid',results.logsGet);136//execution status137app.get('/executionstatus/:id',executionstatus.executionStatusGet);138//machines139app.get('/machines',auth.auth, machines.machinesGet);140app.put('/machines/:id',auth.auth, machines.machinesPut);141app.post('/machines',auth.auth, machines.machinesPost);142app.del('/machines/:id',auth.auth, machines.machinesDelete);143//machineTags144app.get('/machinetags',auth.auth, machinetags.machineTagsGet);145app.post('/machinetags',auth.auth, machinetags.machineTagsPost);146//actions147app.get('/actions',auth.auth, actions.actionsGet);148app.put('/actions/:id',auth.auth, actions.actionsPut);149app.post('/actions',auth.auth, actions.actionsPost);150app.del('/actions/:id',auth.auth, actions.actionsDelete);151//actionTags152app.get('/actiontags',auth.auth, actiontags.actionTagsGet);153app.post('/actiontags',auth.auth, actiontags.actionTagsPost);154//testcases155app.get('/testcases',auth.auth, testcases.testcasesGet);156app.put('/testcases/:id',auth.auth, testcases.testcasesPut);157app.post('/testcases',auth.auth, testcases.testcasesPost);158app.del('/testcases/:id',auth.auth, testcases.testcasesDelete);159//testcaseTags160app.get('/testcasetags',auth.auth, testcaseTags.testcaseTagsGet);161app.post('/testcasetags',auth.auth, testcaseTags.testcaseTagsPost);162//executions163app.get('/executions',auth.auth, executions.executionsGet);164app.put('/executions/:id',auth.auth, executions.executionsPut);165app.post('/executions/:id',executions.executionsPost);166app.del('/executions/:id',auth.auth, executions.executionsDelete);167//executionTags168app.get('/executiontags',auth.auth, executionTags.executionTagsGet);169app.post('/executiontags',auth.auth, executionTags.executionTagsPost);170//executiontestcases171app.get('/executiontestcases/:id',auth.auth, executiontestcases.executiontestcasesGet);172app.put('/executiontestcases/:id',auth.auth, executiontestcases.executiontestcasesPut);173app.put('/executiontestcases',auth.auth, executiontestcases.executiontestcasesPutArray);174app.post('/executiontestcases',auth.auth, executiontestcases.executiontestcasesPost);175app.post('/executiontestcases/udatetestset',auth.auth, executiontestcases.executionsTestSetUpdatePost);176app.del('/executiontestcases/:id',auth.auth, executiontestcases.executiontestcasesDelete);177app.put('/executiontestcasenotes',auth.auth, executiontestcases.executionNotes);178//machineRoles179app.get('/machineroles',auth.auth, machineroles.machineRolesGet);180app.post('/machineroles',auth.auth, machineroles.machineRolesPost);181//users182app.get('/users', auth.auth, users.usersGet);183app.put('/users/:id',auth.auth, users.usersPut);184app.post('/users',auth.auth, users.usersPost);185app.del('/users/:id',auth.auth, users.usersDelete);186app.post('/canadduser',auth.auth, users.canAddUser);187//testsets188app.get('/testsets', auth.auth, testsets.testsetsGet);189app.put('/testsets/:id',auth.auth, testsets.testsetsPut);190app.post('/testsets',auth.auth, testsets.testsetsPost);191app.del('/testsets/:id',auth.auth, testsets.testsetsDelete);192//hosts193app.get('/hosts', auth.auth, hosts.hostsGet);194app.put('/hosts/:id',auth.auth, hosts.hostsPut);195app.post('/hosts',auth.auth, hosts.hostsPost);196app.del('/hosts/:id',auth.auth, hosts.hostsDelete);197//templates198app.get('/templates', auth.auth, templates.templatesGet);199app.put('/templates/:id',auth.auth, templates.templatesPut);200app.post('/templates',auth.auth, templates.templatesPost);201app.del('/templates/:id',auth.auth, templates.templatesDelete);202//userStates203/*204app.get('/userStates', auth.auth, users.userStatesGet);205app.put('/userStates/:id',auth.auth, users.userStatesPut);206app.post('/userStates',auth.auth, users.userStatesPost);207app.del('/userStates/:id',auth.auth, users.userStatesDelete);208*/209//projects210app.get('/projects', auth.auth, projects.projectsGet);211app.put('/projects/:id',auth.auth, projects.projectsPut);212app.post('/projects',auth.auth, projects.projectsPost);213app.del('/projects/:id',auth.auth, projects.projectsDelete);214//userTags215app.get('/userTags',auth.auth, userTags.userTagsGet);216app.post('/userTags',auth.auth, userTags.userTagsPost);217//scripts218app.get('/scripts/root',auth.auth, scripts.scriptsGet);219app.post('/scripts/delete',auth.auth, scripts.scriptsDelete);220app.post('/scripts/copy',auth.auth, scripts.scriptsCopy);221app.post('/scripts/push',auth.auth, scripts.scriptsPush);222app.post('/scripts/pull',scripts.scriptsPull);223//script224app.get('/runpip',auth.auth, script.runPipGet);225app.post('/script/get',auth.auth, script.scriptGet);226app.post('/script/resolveconflict',auth.auth, script.resolveConflict);227app.post('/script',auth.auth, script.scriptPost);228app.put('/script',auth.auth, script.scriptPut);229app.post('/script/mergeinfo',auth.auth, script.mergeInfo);230//folder231app.post('/folder',auth.auth, folder.folderPost);232app.put('/folder',auth.auth, folder.folderPut);233//folder234app.post('/fileupload',auth.auth, fileupload.upload);235//methodFinder236app.post('/methodFinder',auth.auth, methodFinder.methodFinderPost);237common.initLogger("server");238common.parseConfig(function(){239 common.initDB(common.Config.DBPort,function(){240 common.cleanUpExecutions();241 common.cleanUpUserStatus(function(){242 var server = require('http').createServer(app);243 server.listen(common.Config.AppServerPort, function(){244 realtime.initSocket(server);245 common.logger.log("Express server listening on port %d in %s mode", common.Config.AppServerPort, app.settings.env);246 });247 });248 auth.loadSessions();249 });...
UnitTestsView.js
Source:UnitTestsView.js
...41 </div>42 )}43 <LoadingButton44 onClick={() => {45 runUnitTest()46 setRunning(true)47 }}48 isLoading={unitTextDataisPending || isRunning}49 loadingText="Running unit tests"50 variant="outlined"51 >52 Run unit tests53 </LoadingButton>54 <LoadingButton55 onClick={getJunitUnitTestsReport}56 isLoading={junitUnitTestsReportisPending}57 disabled={unitTextDataisPending || isRunning}58 variant="outlined"59 style={{...
testcase.js
Source:testcase.js
...34 this.client = client;35 try {36 let result;37 if (this.context.unitTestsMode) {38 result = this.runUnitTest();39 } else {40 result = this.context.call(this.testName, this.client);41 }42 return result;43 } catch (err) {44 return Promise.reject(err);45 }46 }47 runUnitTest() {48 let unitTest = new UnitTest(this.testName, this.context, {49 asyncHookTimeout: this.settings.globals.unitTestsTimeout50 });51 return unitTest.run(this.client);52 }53}...
run-unit-test.js
Source:run-unit-test.js
1const childProcess = require("child_process")2const fs = require("fs")3const path = require("path")4const isWindows = process.platform === "win32"5function runUnitTest(railwayId) {6 return new Promise((resolve, reject) => {7 const gradlewProcess = childProcess.spawn(8 isWindows ? "gradlew" : "./gradlew",9 [10 ":app:testDebugUnitTest",11 "--tests com.example.techtrain.railway.S" + railwayId,12 "--rerun-tasks",13 "--console=plain",14 "--no-daemon"15 ],16 {17 "shell": true18 }19 )20 gradlewProcess.stdout.on("data", function(data) {21 // Note: `data` might contain line break characters, so use `write` to reproduce the original output.22 process.stdout.write(data.toString())23 })24 gradlewProcess.on("close", function(code) {25 return resolve()26 })27 gradlewProcess.on("exit", function(code) {28 return resolve()29 })30 gradlewProcess.on("error", function(err) {31 return reject()32 })33 })34}35async function run() {36 const railwayId = parseInt(process.argv[2]).toString()37 try {38 await runUnitTest(railwayId)39 } catch (err) {40 console.log("Error on runUnitTest" + err.message)41 }42 const resultXml = path.resolve("./app/build/test-results/testDebugUnitTest/TEST-com.example.techtrain.railway.S" + railwayId + ".xml")43 if (!fs.existsSync(resultXml)) {44 fs.mkdirSync(path.resolve("./app/build/test-results/testDebugUnitTest/"), { "recursive" : true })45 const compileErrorResultXml = path.resolve("./.techtrain/utils/compile-error.xml")46 fs.copyFileSync(compileErrorResultXml, resultXml)47 }48}...
run-all-unit-tests.js
Source:run-all-unit-tests.js
1const path = require('path')2const shell = require('shelljs')3const chalk = require('chalk')4const figlet = require('figlet')5var printInformation = function (information) {6 shell.echo('')7 shell.echo(chalk.gray(information))8 shell.echo('')9}10shell.echo(chalk.green.bold(figlet.textSync('testing...', 'Computer')))11printInformation('running all unit tests')12function runUnitTest (service) {13 shell.cd(path.join(__dirname, `../${service}/unittests`))14 printInformation('running (dotnet core xunit) unit tests in ' + shell.pwd())15 if (shell.exec('dotnet test').code !== 0) {16 printInformation(`/${service}/unittests failed\n`)17 return false18 } else {19 printInformation(`/${service}/unittests passed\n`)20 return true21 }22}23var allTestsPassed = (a, b) => {24 let prevPassed = a === true25 return prevPassed && b === true26}27var servicesWithTests = ['tracker', 'analyzer', 'storage']28var allPassed = servicesWithTests.map(runUnitTest).reduce(allTestsPassed, true)29if (allPassed) {30 shell.echo(chalk.green('all tests passed'))31} else {32 shell.echo(chalk.red('tests failed'))...
Uize.Build.RunUnitTest.js
Source:Uize.Build.RunUnitTest.js
1/*______________2| ______ | U I Z E J A V A S C R I P T F R A M E W O R K3| / / | ---------------------------------------------------4| / O / | MODULE : Uize.Build.RunUnitTest Package5| / / / |6| / / / /| | ONLINE : http://www.uize.com7| /____/ /__/_| | COPYRIGHT : (c)2012 UIZE8| /___ | LICENSE : Available under MIT License or GNU General Public License9|_______________| http://www.uize.com/license.html10*/11/* Module Meta Data12 type: Package13 importance: 114 codeCompleteness: 10015 testCompleteness: 016 docCompleteness: 217*/18/*?19 Introduction20 The =Uize.Build.RunUnitTest= module provides a method for testing a specified JavaScript module.21 *DEVELOPERS:* `Chris van Rensburg`22*/23Uize.module ({24 name:'Uize.Build.RunUnitTest',25 required:'Uize.Build.Util',26 builder:function () {27 var _package = function () {};28 /*** Public Static Methods ***/29 _package.perform = function (_params) {30 Uize.Build.Util.runUnitTests (_params.testModule,_params.silent == 'true');31 };32 return _package;33 }...
test.js
Source:test.js
1const programmingTest = require("./isMatchingCurlyBrackets.js");2const assert = require('assert');3describe('Unit Tests â isMatchingBrackets(str) function', () => {4 5 runUnitTest("{}", true);6 runUnitTest("}{", false);7 runUnitTest("{{}", false);8 runUnitTest("", true);9 runUnitTest("{abc...xyz}", true);10 runUnitTest("{{}}{}{{{}{{}}{}}}", true);11 runUnitTest("{{{{{{{{", false);12 runUnitTest("}}}}}}}", false);13 runUnitTest("{asdc{asdcsd}}{asdcasdcadsc}{{{asdcasdc}{{}}.!@#@#@!!@#{}}}", true);14 runUnitTest("this is my unit test", true);15});16function runUnitTest(argument, expected) {17 it(`should return ${expected} when passing â "${argument}" â as an argument`, () => {18 assert.equal(programmingTest.isMatchingBrackets(argument), expected); 19 });...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 page.on('console', msg => console.log('PAGE LOG:', msg.text()));6 await page.waitForSelector('body');7 await page.evaluate(() => runUnitTest());8 await page.waitFor(2000);9 await browser.close();10})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const { runUnitTest } = require('puppeteer-unit-test');3(async () => {4 const browser = await puppeteer.launch({5 });6 const page = await browser.newPage();7 await runUnitTest(page, {8 });9 await browser.close();10})();11const puppeteer = require('puppeteer');12const { jest: puppeteerJest } = require('puppeteer-unit-test');13describe('My Puppeteer Unit Test', () => {14 let browser;15 let page;16 beforeAll(async () => {17 browser = await puppeteer.launch({18 });19 page = await browser.newPage();20 });21 afterAll(async () => {22 await browser.close();23 });24 it('should pass', async () => {25 await page.waitForSelector('input[name="q"]');26 await page.type('input[name="q"]', 'puppeteer');27 await page.keyboard.press('Enter');28 await page.waitForSelector('h3');29 await puppeteerJest.expect(page).toMatch('Puppeteer');30 });31});
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.runUnitTest();6 await browser.close();7})();8const puppeteer = require('puppeteer');9async function runUnitTest() {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.runUnitTest();13 await browser.close();14}15module.exports = { runUnitTest };16const puppeteer = require('puppeteer');17async function runUnitTest() {18 const browser = await puppeteer.launch();19 const page = await browser.newPage();20 await page.runUnitTest();21 await browser.close();22}23module.exports = { runUnitTest };
Using AI Code Generation
1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { runUnitTest } = require('puppeteer-istanbul');5(async () => {6 const browser = await puppeteer.launch({headless: false});7 const page = await browser.newPage();8 fs.writeFileSync(path.join(__dirname, 'coverage.json'), JSON.stringify(coverage));9 await browser.close();10})();11describe('My Test', () => {12 it('should do something', () => {13 assert(1 + 1 === 2);14 });15});16{17 "scripts": {18 },19 "devDependencies": {20 }21}
Using AI Code Generation
1const puppeteer = require('puppeteer');2const path = require('path');3const fs = require('fs');4const { exec } = require('child_process');5const config = require('./config.json');6const { runUnitTest } = require('./puppeteer.js');7const { runUnitTest } = require('./puppeteer.js');8const { runUnitTest } = require('./puppeteer.js');9(async () => {10 const browser = await puppeteer.launch({ headless: false, args: ['--no-sandbox', '--disable-setuid-sandbox'] });11 const page = await browser.newPage();12 await page.setViewport({ width: 1920, height: 1080 });13 await page.waitForSelector('#root');14 await runUnitTest(page, 'test1');15 await runUnitTest(page, 'test2');16 await runUnitTest(page, 'test3');17 await browser.close();18})();19const puppeteer = require('puppeteer');20const path = require('path');21const fs = require('fs');22const { exec } = require('child_process');23const config = require('./config.json');24const { runUnitTest } = require('./puppeteer.js');25const { runUnitTest } = require('./puppeteer.js');26const { runUnitTest } = require('./puppeteer.js');27(async () => {28 const browser = await puppeteer.launch({ headless: false, args: ['--no-sandbox', '--disable-setuid-sandbox'] });29 const page = await browser.newPage();30 await page.setViewport({ width: 1920, height: 1080 });31 await page.waitForSelector('#root');32 await runUnitTest(page, 'test1');33 await runUnitTest(page, 'test2');34 await runUnitTest(page, 'test3');35 await browser.close();36})();37const puppeteer = require('puppeteer');38const path = require('path');39const fs = require('fs');40const { exec } = require('child_process');41const config = require('./config.json');42const { runUnitTest } = require('./puppeteer.js');43const { runUnitTest } = require('./puppeteer.js');44const { runUnitTest } = require('./p
Using AI Code Generation
1const puppeteer = require('puppeteer');2const assert = require('assert');3const { runUnitTest } = require('puppeteer-test-runner');4const { expect } = require('chai');5const test = async () => {6 const browser = await puppeteer.launch();7 const page = await browser.newPage();8 const title = await page.title();9 expect(title).to.equal('Google');10 await browser.close();11};12runUnitTest(test);
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!!