How to use Runnable method in Mocha

Best JavaScript code snippet using mocha

SimplePipeRequest.js

Source:SimplePipeRequest.js Github

copy

Full Screen

1$_J("net.sf.j2s.ajax");2$_L(["net.sf.j2s.ajax.SimpleRPCRequest"],"net.sf.j2s.ajax.SimplePipeRequest",["net.sf.j2s.ajax.HttpRequest","$.SimplePipeHelper","$.SimpleSerializable","$.XHRCallbackAdapter"],function(){3c$=$_T(net.sf.j2s.ajax,"SimplePipeRequest",net.sf.j2s.ajax.SimpleRPCRequest);4c$.getPipeMode=$_M(c$,"getPipeMode",5function(){6return net.sf.j2s.ajax.SimplePipeRequest.pipeMode;7});8c$.getQueryInterval=$_M(c$,"getQueryInterval",9function(){10return net.sf.j2s.ajax.SimplePipeRequest.pipeQueryInterval;11});12c$.switchToQueryMode=$_M(c$,"switchToQueryMode",13function(){14($t$=net.sf.j2s.ajax.SimplePipeRequest.pipeMode=3,net.sf.j2s.ajax.SimplePipeRequest.prototype.pipeMode=net.sf.j2s.ajax.SimplePipeRequest.pipeMode,$t$);15($t$=net.sf.j2s.ajax.SimplePipeRequest.pipeQueryInterval=1000,net.sf.j2s.ajax.SimplePipeRequest.prototype.pipeQueryInterval=net.sf.j2s.ajax.SimplePipeRequest.pipeQueryInterval,$t$);16});17c$.switchToQueryMode=$_M(c$,"switchToQueryMode",18function(ms){19($t$=net.sf.j2s.ajax.SimplePipeRequest.pipeMode=3,net.sf.j2s.ajax.SimplePipeRequest.prototype.pipeMode=net.sf.j2s.ajax.SimplePipeRequest.pipeMode,$t$);20if(ms<0){21ms=1000;22}($t$=net.sf.j2s.ajax.SimplePipeRequest.pipeQueryInterval=ms,net.sf.j2s.ajax.SimplePipeRequest.prototype.pipeQueryInterval=net.sf.j2s.ajax.SimplePipeRequest.pipeQueryInterval,$t$);23},"~N");24c$.switchToContinuumMode=$_M(c$,"switchToContinuumMode",25function(){26($t$=net.sf.j2s.ajax.SimplePipeRequest.pipeMode=4,net.sf.j2s.ajax.SimplePipeRequest.prototype.pipeMode=net.sf.j2s.ajax.SimplePipeRequest.pipeMode,$t$);27});28c$.constructRequest=$_M(c$,"constructRequest",29function(pipeKey,pipeRequestType){30($t$=net.sf.j2s.ajax.SimplePipeRequest.reqCount++,net.sf.j2s.ajax.SimplePipeRequest.prototype.reqCount=net.sf.j2s.ajax.SimplePipeRequest.reqCount,$t$);31return"k"+"="+pipeKey+"&"+"t"+"="+pipeRequestType+"&"+"r"+"="+net.sf.j2s.ajax.SimplePipeRequest.reqCount;32},"~S,~S");33c$.sendRequest=$_M(c$,"sendRequest",34function(request,method,url,data,async){35if("GET".equals(method.toUpperCase())){36request.open(method,url+(url.indexOf('?')!=-1?"&":"?")+data,async);37request.send(null);38}else{39request.open(method,url,async);40request.send(data);41}},"net.sf.j2s.ajax.HttpRequest,~S,~S,~S,~B");42c$.pipe=$_M(c$,"pipe",43function(runnable){44runnable.ajaxIn();45net.sf.j2s.ajax.SimplePipeRequest.pipeRequest(runnable);46},"net.sf.j2s.ajax.SimplePipeRunnable");47c$.disableESCKeyConnectionAbsorting=$_M(c$,"disableESCKeyConnectionAbsorting",48($fz=function(){49Clazz.addEvent(document,"keydown",function(e){50var ie=false;51if(e==null){52e=window.event;53ie=true;54}55var key=e.keyCode||e.charCode;56if(key==27){57if(ie){58e.returnValue=false;59}else{60e.preventDefault();61}62return false;63}64});65},$fz.isPrivate=true,$fz));66c$.pipeRequest=$_M(c$,"pipeRequest",67($fz=function(runnable){68if(!net.sf.j2s.ajax.SimplePipeRequest.escKeyAbortingDisabled){69($t$=net.sf.j2s.ajax.SimplePipeRequest.escKeyAbortingDisabled=true,net.sf.j2s.ajax.SimplePipeRequest.prototype.escKeyAbortingDisabled=net.sf.j2s.ajax.SimplePipeRequest.escKeyAbortingDisabled,$t$);70net.sf.j2s.ajax.SimplePipeRequest.disableESCKeyConnectionAbsorting();71}var url=runnable.getHttpURL();72var method=runnable.getHttpMethod();73var serialize=runnable.serialize();74if(method==null){75method="POST";76}var ajaxOut=null;77{78ajaxOut=runnable.ajaxOut;79if(ajaxOut.wrapped!=true){80runnable.ajaxOut=(function(aO,r){81return function(){82aO.apply(r,[]);83r.ajaxOut=aO;84net.sf.j2s.ajax.SimplePipeRequest.ajaxPipe(r);85};86})(ajaxOut,runnable);87runnable.ajaxOut.wrapped=true;88}89}if(net.sf.j2s.ajax.SimpleRPCRequest.checkXSS(url,serialize,runnable)){90return;91}{92runnable.ajaxOut=ajaxOut;93}var url2=net.sf.j2s.ajax.SimpleRPCRequest.adjustRequestURL(method,url,serialize);94if(url2!==url){95serialize=null;96}var request=net.sf.j2s.ajax.SimpleRPCRequest.getRequest();97request.open(method,url,true);98request.registerOnReadyStateChange((($_D("net.sf.j2s.ajax.SimplePipeRequest$3")?0:net.sf.j2s.ajax.SimplePipeRequest.$SimplePipeRequest$3$()),$_N(net.sf.j2s.ajax.SimplePipeRequest$3,this,$_F("request",request,"runnable",runnable))));99request.send(serialize);100},$fz.isPrivate=true,$fz),"net.sf.j2s.ajax.SimplePipeRunnable");101c$.updatePipeByURL=$_M(c$,"updatePipeByURL",102function(pipeID,url){103if(url==null||url.length==0){104return;105}106var map=net.sf.j2s.ajax.SimplePipeRequest.pipeScriptMap;107var pipe=map[url];108if(pipe!=null&&pipeID!=null&&pipeID.length>0){109var stillExistedRequest=false;110var idPrefix=pipeID;111var idx=pipeID.lastIndexOf("-");112if(idx!=-1){113idPrefix=pipeID.substring(0,idx);114}115var iframes=document.getElementsByTagName("IFRAME");116for(var i=0;i<iframes.length;i++){117var el=iframes[i];118if(el.id!=null&&el.id.indexOf(idPrefix)==0){119stillExistedRequest=true;120break;121}122}123if(!stillExistedRequest){124var scripts=document.getElementsByTagName("SCRIPT");125for(var i=0;i<scripts.length;i++){126var el=scripts[i];127if(el.id!=null&&el.id.indexOf(idPrefix)==0){128stillExistedRequest=true;129break;130}131}132}133pipe.queryEnded=!stillExistedRequest;134delete map[url];135}136},"~S,~S");137c$.generatePipeScriptCallback=$_M(c$,"generatePipeScriptCallback",138function(pipeID){139return function(){140if(pipeID!=null){141var pw=window.parent;142if(pw==null||pw["net"]==null)return;143if(!pw.net.sf.j2s.ajax.SimpleRPCRequest.cleanUp(this)){144return;145}146var url=this.url;147this.url=null;148document.getElementsByTagName("HEAD")[0].removeChild(this);149var iframe=pw.document.getElementById(pipeID);150if(iframe!=null){151iframe.parentNode.removeChild(iframe);152}153pw.net.sf.j2s.ajax.SimplePipeRequest.updatePipeByURL(pipeID,url);154}else{155if(window==null||window["net"]==null)return;156if(!net.sf.j2s.ajax.SimpleRPCRequest.cleanUp(this)){157return;158}159var url=this.url;160this.url=null;161document.getElementsByTagName("HEAD")[0].removeChild(this);162net.sf.j2s.ajax.SimplePipeRequest.updatePipeByURL(pipeID,url);163}164};165},"~S");166c$.loadPipeScript=$_M(c$,"loadPipeScript",167function(url){168var script=document.createElement("SCRIPT");169script.type="text/javascript";170script.src=url;171script.url=url;172var pipeID=arguments[1];173if(pipeID!=null&&pipeID.length>0){174script.id=pipeID;175}176var userAgent=navigator.userAgent.toLowerCase();177var isOpera=(userAgent.indexOf("opera")!=-1);178var isIE=(userAgent.indexOf("msie")!=-1)&&!isOpera;179var fun=net.sf.j2s.ajax.SimplePipeRequest.generatePipeScriptCallback(pipeID);180script.defer=true;181if(typeof(script.onreadystatechange)=="undefined"||!isIE){182script.onload=script.onerror=fun;183}else{184script.onreadystatechange=fun;185}186var head=document.getElementsByTagName("HEAD")[0];187head.appendChild(script);188},"~S");189c$.loadPipeIFrameScript=$_M(c$,"loadPipeIFrameScript",190function(pipeKey,url){191var iframe=document.createElement("IFRAME");192iframe.style.display="none";193var pipeID=null;194do{195pipeID="pipe-script-"+pipeKey+"-"+Math.round(10000000*Math.random());196}while(document.getElementById(pipeID)!=null);197iframe.id=pipeID;198document.body.appendChild(iframe);199var html="<html><head><title></title>";200html+="<script type=\"text/javascript\">\r\n";201html+="window[\"$p1p3p$\"] = function (string) {\r\n";202html+=" with (window.parent) {\r\n";203html+=" net.sf.j2s.ajax.SimplePipeRequest.parseReceived (string);\r\n";204html+=" };\r\n";205html+="};\r\n";206html+="window[\"$p1p3b$\"] = function (key, result) {\r\n";207html+=" with (window.parent) {\r\n";208html+=" net.sf.j2s.ajax.SimplePipeRequest.pipeNotifyCallBack (key, result);\r\n";209html+=" };\r\n";210html+="};\r\n";211html+="</scr"+"ipt></head><body><script type=\"text/javascript\">\r\n";212if(ClassLoader.isOpera)213html+="window.setTimeout (function () {\r\n";214html+="net = { sf : { j2s : { ajax : { SimplePipeRequest : { generatePipeScriptCallback : "+net.sf.j2s.ajax.SimplePipeRequest.generatePipeScriptCallback+" } } } } };\r\n";215html+="("+net.sf.j2s.ajax.SimplePipeRequest.loadPipeScript+") (";216html+="\""+url.replace(/"/g,"\\\"")+"\", \""+pipeID+"\"";217html+=");\r\n";218if(ClassLoader.isOpera)219html+="}, "+(net.sf.j2s.ajax.SimplePipeRequest.pipeQueryInterval>>2)+");\r\n";220html+="</scr"+"ipt></body></html>";221net.sf.j2s.ajax.SimplePipeRequest.iframeDocumentWrite(iframe,html);222},"~S,~S");223c$.generateLazyIframeWriting=$_M(c$,"generateLazyIframeWriting",224function(handle,domain,html){225return function(){226try{227var doc=handle.contentWindow.document;228doc.open();229if(ClazzLoader.isIE&&window["xss.domain.enabled"]==true230&&domain!=null&&domain.length>0){231try{232doc.domain=domain;233}catch(e){}234}235doc.write(html);236doc.close();237document.title=document.title;238handle=null;239}catch(e){240window.setTimeout(arguments.callee,25);241}242};243},"~O,~S,~S");244c$.iframeDocumentWrite=$_M(c$,"iframeDocumentWrite",245function(handle,html){246var handle=arguments[0];247var html=arguments[1];248var domain=null;249try{250domain=document.domain;251}catch(e){}252if(ClazzLoader.isIE&&window["xss.domain.enabled"]==true253&&domain!=null&&domain.length>0){254document.domain=domain;255}256try{257if(handle.contentWindow!=null){258if(ClazzLoader.isIE&&window["xss.domain.enabled"]==true259&&domain!=null&&domain.length>0){260handle.contentWindow.location="javascript:document.open();document.domain='"+domain+"';document.close();void(0);";261}else{262handle.contentWindow.location="about:blank";263}264}else{265handle.src="about:blank";266}267}catch(e){268}269try{270var doc=handle.contentWindow.document;271doc.open();272if(ClazzLoader.isIE&&window["xss.domain.enabled"]==true273&&domain!=null&&domain.length>0){274doc.domain=domain;275}276doc.write(html);277doc.close();278document.title=document.title;279}catch(e){280window.setTimeout(net.sf.j2s.ajax.SimplePipeRequest.generateLazyIframeWriting(handle,domain,html),25);281}282},"~O,~S");283c$.pipeScript=$_M(c$,"pipeScript",284function(runnable){285var url=runnable.getPipeURL();286var requestURL=url+(url.indexOf('?')!=-1?"&":"?")+net.sf.j2s.ajax.SimplePipeRequest.constructRequest(runnable.pipeKey,"x");287{288net.sf.j2s.ajax.SimplePipeRequest.pipeScriptMap[requestURL]=runnable;289}if(net.sf.j2s.ajax.SimpleRPCRequest.isXSSMode(url)){290var ok4IFrameScript=true;291{292var domain=null;293try{294domain=document.domain;295}catch(e){296}297ok4IFrameScript=(domain!=null&&domain.length>0)||navigator.userAgent.toLowerCase().indexOf("msie")==-1;298}if(ok4IFrameScript){299net.sf.j2s.ajax.SimplePipeRequest.loadPipeIFrameScript(runnable.pipeKey,requestURL);300return;301}}{302var pipeID=null;303do{304pipeID="pipe-script-"+runnable.pipeKey+"-"+Math.round(10000000*Math.random());305}while(document.getElementById(pipeID)!=null);306net.sf.j2s.ajax.SimplePipeRequest.loadPipeScript(requestURL,pipeID);307}},"net.sf.j2s.ajax.SimplePipeRunnable");308c$.pipeSubdomainQuery=$_M(c$,"pipeSubdomainQuery",309function(runnable,domain){310var pipeKey=runnable.pipeKey;311var spr=net.sf.j2s.ajax.SimplePipeRequest;312spr.pipeIFrameClean(pipeKey);313var ifr=document.createElement("IFRAME");314ifr.style.display="none";315var url=runnable.getPipeURL();316var src=url+(url.indexOf('?')!=-1?"&":"?")317+spr.constructRequest(pipeKey,spr.PIPE_TYPE_SUBDOMAIN_QUERY)318+"&"+spr.FORM_PIPE_DOMAIN+"="+domain;319ifr.id="pipe-"+pipeKey;320ifr.src=src;321document.body.appendChild(ifr);322},"net.sf.j2s.ajax.SimplePipeRunnable,~S");323c$.pipeNotify=$_M(c$,"pipeNotify",324function(runnable){325var url=runnable.getPipeURL();326net.sf.j2s.ajax.SimplePipeRequest.loadPipeScript(url+(url.indexOf('?')!=-1?"&":"?")+net.sf.j2s.ajax.SimplePipeRequest.constructRequest(runnable.pipeKey,"n"));327},"net.sf.j2s.ajax.SimplePipeRunnable");328c$.pipeNotifyCallBack=$_M(c$,"pipeNotifyCallBack",329function(key,result){330if("l".equals(result)){331var pipe=net.sf.j2s.ajax.SimplePipeHelper.getPipe(key);332if(pipe!=null){333pipe.pipeAlive=false;334pipe.pipeLost();335net.sf.j2s.ajax.SimplePipeHelper.removePipe(key);336}}},"~S,~S");337c$.pipeQuery=$_M(c$,"pipeQuery",338function(runnable){339var pipeRequest=net.sf.j2s.ajax.SimpleRPCRequest.getRequest();340var pipeKey=runnable.pipeKey;341var pipeMethod=runnable.getPipeMethod();342var pipeURL=runnable.getPipeURL();343pipeRequest.registerOnReadyStateChange((($_D("net.sf.j2s.ajax.SimplePipeRequest$4")?0:net.sf.j2s.ajax.SimplePipeRequest.$SimplePipeRequest$4$()),$_N(net.sf.j2s.ajax.SimplePipeRequest$4,this,$_F("pipeRequest",pipeRequest,"runnable",runnable))));344var pipeRequestData=net.sf.j2s.ajax.SimplePipeRequest.constructRequest(pipeKey,"q");345var async=false;346{347async=true;348var key="xhr."+pipeKey+"."+pipeRequestData;349net.sf.j2s.ajax.SimplePipeRequest.pipeQueryMap[key]=pipeRequest;350}net.sf.j2s.ajax.SimplePipeRequest.sendRequest(pipeRequest,pipeMethod,pipeURL,pipeRequestData,async);351},"net.sf.j2s.ajax.SimplePipeRunnable");352c$.getRequestWithMonitor=$_M(c$,"getRequestWithMonitor",353function(montior){354{355}return(($_D("net.sf.j2s.ajax.SimplePipeRequest$5")?0:net.sf.j2s.ajax.SimplePipeRequest.$SimplePipeRequest$5$()),$_N(net.sf.j2s.ajax.SimplePipeRequest$5,this,$_F("montior",montior)));356},"net.sf.j2s.ajax.HttpRequest.IXHRReceiving");357c$.pipeContinuum=$_M(c$,"pipeContinuum",358function(runnable){359var pipeKey=runnable.pipeKey;360var spr=net.sf.j2s.ajax.SimplePipeRequest;361spr.pipeIFrameClean(pipeKey);362var subdomain=arguments[1];363var pipeContinued=arguments[2];364(function(){365var ifr=document.createElement("IFRAME");366ifr.style.display="none";367ifr.id="pipe-"+pipeKey;368var url=runnable.getPipeURL();369if(subdomain==null){370document.domain=document.domain;371window["xss.domain.enabled"]=true;372}373ifr.src=url+(url.indexOf('?')!=-1?"&":"?")374+spr.constructRequest(pipeKey,spr.PIPE_TYPE_SCRIPT)375+(subdomain==null?""376:"&"+spr.FORM_PIPE_DOMAIN+"="+subdomain);377document.body.appendChild(ifr);378})();379if(pipeContinued==true){380return;381}382var fun=(function(key,created){383return function(){384var sph=net.sf.j2s.ajax.SimplePipeHelper;385var runnable=sph.getPipe(key);386if(runnable!=null){387var spr=net.sf.j2s.ajax.SimplePipeRequest;388var now=new Date().getTime();389var last=runnable.lastPipeDataReceived;390if(last<=0){391last=created;392}393if(now-last>3*spr.pipeLiveNotifyInterval){394runnable.pipeAlive=false;395runnable.pipeClosed();396sph.removePipe(key);397spr.pipeIFrameClean(key);398}else{399spr.pipeNotify(runnable);400window.setTimeout(arguments.callee,spr.pipeLiveNotifyInterval);401}402}403};404})(runnable.pipeKey,new Date().getTime());405window.setTimeout(fun,spr.pipeLiveNotifyInterval);406},"net.sf.j2s.ajax.SimplePipeRunnable");407c$.pipeIFrameClean=$_M(c$,"pipeIFrameClean",408function(pipeKey){409var urlSignature=net.sf.j2s.ajax.SimplePipeRequest.FORM_PIPE_KEY+"="+pipeKey+"&";410var iframes=document.getElementsByTagName("IFRAME");411for(var i=0;i<iframes.length;i++){412var el=iframes[i];413var url=null;414try{415url=el.src;416}catch(e){417}418if(url==null||url.length==0){419try{420url=el.contentWindow.location.toString();421}catch(e){422}423}424if(url!=null&&url.indexOf(urlSignature)==0){425el.parentNode.removeChild(el);426continue;427}428if(el.id==pipeKey||el.id=="pipe-"+pipeKey){429el.parentNode.removeChild(el);430continue;431}432}433},"~S");434c$.parseReceived=$_M(c$,"parseReceived",435function(string){436if(string==null){437return null;438}var ss=null;439var start=0;440while(string.length>start+6){441var destroyedKey="d";442var end=start+6;443if(destroyedKey.equals(string.substring(end,end+destroyedKey.length))){444var key=string.substring(start,end);445var pipe=net.sf.j2s.ajax.SimplePipeHelper.getPipe(key);446if(pipe!=null){447pipe.pipeAlive=false;448pipe.pipeClosed();449net.sf.j2s.ajax.SimplePipeHelper.removePipe(key);450}return string.substring(end+destroyedKey.length);451}var okKey="o";452end=start+6;453if(okKey.equals(string.substring(end,end+okKey.length))){454var key=string.substring(start,end);455var runnable=net.sf.j2s.ajax.SimplePipeHelper.getPipe(key);456if(runnable!=null){457runnable.lastPipeDataReceived=System.currentTimeMillis();458}start=end+okKey.length;459if(start==string.length){460return string.substring(start);461}}var isJavaScript=false;462{463isJavaScript=true;464}if(isJavaScript){465var continueKey="e";466end=start+6;467if(continueKey.equals(string.substring(end,end+continueKey.length))){468var key=string.substring(start,end);469var runnable=net.sf.j2s.ajax.SimplePipeHelper.getPipe(key);470if(runnable!=null){471runnable.lastPipeDataReceived=System.currentTimeMillis();472net.sf.j2s.ajax.SimplePipeRequest.pipeIFrameClean(runnable.pipeKey);473var pipeURL=runnable.getPipeURL();474var isXSS=net.sf.j2s.ajax.SimpleRPCRequest.isXSSMode(pipeURL);475var isSubdomain=false;476if(isXSS){477isSubdomain=net.sf.j2s.ajax.SimpleRPCRequest.isSubdomain(pipeURL);478}var subdomain=net.sf.j2s.ajax.SimplePipeRequest.adjustSubdomain(isSubdomain);479{480net.sf.j2s.ajax.SimplePipeRequest.pipeContinuum(runnable,subdomain,true);481}}return string.substring(end+continueKey.length);482}}ss=net.sf.j2s.ajax.SimpleSerializable.parseInstance(string,end);483if(ss==null||!ss.deserialize(string,end)){484break;485}if(ss!==net.sf.j2s.ajax.SimpleSerializable.UNKNOWN){486var key=string.substring(start,end);487var runnable=net.sf.j2s.ajax.SimplePipeHelper.getPipe(key);488if(runnable!=null){489runnable.lastPipeDataReceived=System.currentTimeMillis();490runnable.deal(ss);491}}start=net.sf.j2s.ajax.SimplePipeRequest.restStringIndex(string,start);492}493if(start!=0){494return string.substring(start);495}return string;496},"~S");497c$.restStringIndex=$_M(c$,"restStringIndex",498function(string,start){499var idx1=string.indexOf('#',start)+1;500var idx2=string.indexOf('$',idx1);501var sizeStr=string.substring(idx1,idx2);502sizeStr=sizeStr.replaceFirst("^0+","");503var size=0;504if(sizeStr.length!=0){505try{506size=Integer.parseInt(sizeStr);507}catch(e){508if($_O(e,NumberFormatException)){509}else{510throw e;511}512}513}var end=idx2+size+1;514if(end<=string.length){515return end;516}else{517return start;518}},"~S,~N");519c$.adjustSubdomain=$_M(c$,"adjustSubdomain",520function(isSubdomain){521var subdomain=null;522if(isSubdomain){523try{524subdomain=window.location.host;525}catch(e){}526if(subdomain!=null){527var idx=subdomain.indexOf(":");528if(idx!=-1){529subdomain=subdomain.substring(0,idx);530}531document.domain=subdomain;532window["xss.domain.enabled"]=true;533}534}535return subdomain;536},"~B");537c$.ajaxPipe=$_M(c$,"ajaxPipe",538function(runnable){539net.sf.j2s.ajax.SimplePipeHelper.registerPipe(runnable.pipeKey,runnable);540var pipeURL=runnable.getPipeURL();541var isXSS=net.sf.j2s.ajax.SimpleRPCRequest.isXSSMode(pipeURL);542var isSubdomain=false;543if(isXSS){544isSubdomain=net.sf.j2s.ajax.SimpleRPCRequest.isSubdomain(pipeURL);545}if((!isXSS||isSubdomain)&&net.sf.j2s.ajax.SimplePipeRequest.pipeMode==4){546var spr=net.sf.j2s.ajax.SimplePipeRequest;547var subdomain=spr.adjustSubdomain(isSubdomain);548spr.pipeContinuum(runnable,subdomain,false);549}else{550var spr=net.sf.j2s.ajax.SimplePipeRequest;551if(isXSS&&isSubdomain&&spr.isSubdomainXSSSupported()){552var subdomain=spr.adjustSubdomain(isSubdomain);553spr.pipeSubdomainQuery(runnable,subdomain);554return;555}556runnable.queryEnded=true;557(function(pipeFun,key,created,lastXHR){558return function(){559var sph=net.sf.j2s.ajax.SimplePipeHelper;560var runnable=sph.getPipe(key);561if(runnable!=null){562var spr=net.sf.j2s.ajax.SimplePipeRequest;563var now=new Date().getTime();564var last=runnable.lastPipeDataReceived;565if(last<=0){566last=created;567}568if((runnable.queryEnded||(now-last>=spr.pipeLiveNotifyInterval569&&(lastXHR==-1||now-lastXHR>=spr.pipeLiveNotifyInterval)))570&&runnable.queryFailedRetries<3){571runnable.queryEnded=false;572if(runnable.received==runnable.lastPipeDataReceived573&&runnable.retries==runnable.queryFailedRetries){574runnable.queryFailedRetries++;575}576pipeFun(runnable);577lastXHR=new Date().getTime();578}579runnable.retries=runnable.queryFailedRetries;580runnable.received=runnable.lastPipeDataReceived;581if(runnable.queryFailedRetries>=3582||now-last>3*spr.pipeLiveNotifyInterval){583runnable.pipeAlive=false;584runnable.pipeClosed();585sph.removePipe(key);586spr.pipeIFrameClean(key);587}else{588window.setTimeout(arguments.callee,spr.pipeQueryInterval);589}590}591};592})((!isXSS)?spr.pipeQuery:spr.pipeScript,runnable.pipeKey,new Date().getTime(),-1)();593}},"net.sf.j2s.ajax.SimplePipeRunnable");594c$.isSubdomainXSSSupported=$_M(c$,"isSubdomainXSSSupported",595function(){596var ua=navigator.userAgent;597var name="Opera";598var idx=ua.indexOf(name);599if(idx!=-1){600return parseFloat(ua.substring(idx+name.length+1))>=9.6;601}602name="Firefox";603idx=ua.indexOf(name);604if(idx!=-1){605return parseFloat(ua.substring(idx+name.length+1))>=1.5;606}607name="MSIE";608idx=ua.indexOf(name);609if(idx!=-1){610return parseFloat(ua.substring(idx+name.length+1))>=6.0;611}612return true;613});614c$.subdomainInit=$_M(c$,"subdomainInit",615function(p){616if(window["NullObject"]==null){617window["NullObject"]=function(){};618}619p.initParameters=function(){620this.parentDomain=document.domain;621this.pipeQueryInterval=1000;622this.pipeLiveNotifyInterval=25000;623this.runnable=null;624this.lastXHR=-1;625var oThis=this;626with(window.parent){627var sph=net.sf.j2s.ajax.SimplePipeHelper;628var spr=net.sf.j2s.ajax.SimplePipeRequest;629this.runnable=sph.getPipe(this.key);630this.pipeQueryInterval=spr.getQueryInterval();631this.pipeLiveNotifyInterval=spr.pipeLiveNotifyInterval;632}633if(this.runnable==null){634eval("("+window.parent.net.sf.j2s.ajax.SimplePipeRequest.checkIFrameSrc+") ();");635}else{636this.runnable.queryEnded=true;637}638};639p.initHttpRequest=function(){640this.xhrHandle=null;641if(window.XMLHttpRequest){642this.xhrHandle=new XMLHttpRequest();643}else{644try{645this.xhrHandle=new ActiveXObject("Msxml2.XMLHTTP");646}catch(e){647this.xhrHandle=new ActiveXObject("Microsoft.XMLHTTP");648}649}650var oThis=this;651this.xhrHandle.onreadystatechange=function(){652if(oThis.xhrHandle==null){653oThis=null;654return;655}656var state=oThis.xhrHandle.readyState;657if(state==4){658var pipeData=oThis.xhrHandle.responseText;659oThis.xhrHandle.onreadystatechange=NullObject;660var pipe=oThis.runnable;661document.domain=oThis.parentDomain;662if(oThis.xhrHandle.status!=200){663pipe.queryFailedRetries++;664}else{665pipe.queryFailedRetries=0;666with(window.parent){667net.sf.j2s.ajax.SimplePipeRequest.parseReceived(pipeData);668oThis.runnable=net.sf.j2s.ajax.SimplePipeHelper.getPipe(oThis.key);669}670}671pipe.queryEnded=true;672var xhrHandle=oThis.xhrHandle;673with(window.parent){674var pqMap=net.sf.j2s.ajax.SimplePipeRequest.pipeQueryMap;675for(var key in pqMap){676if(typeof key=="string"&&key.indexOf("xhr."+pipe.pipeKey+".")==0){677if(pqMap[key]==null||pqMap[key]===xhrHandle){678delete pqMap[key];679}else{680delete pqMap[key];681pipe.queryEnded=false;682}683}684}685}686oThis.xhrHandle=null;687oThis=null;688}689};690};691p.pipeXHRQuery=function(request,method,url,data){692if("GET"==method.toUpperCase()){693request.open(method,url+(data!=null?((url.indexOf('?')!=-1?"&":"?")+data):""),true,null,null);694data=null;695}else{696request.open(method,url,true,null,null);697}698if(method!=null&&method.toLowerCase()=="post"){699try{700request.setRequestHeader("Content-type",701"application/x-www-form-urlencoded");702}catch(e){703}704}705request.send(data);706};707p.initParameters();708},"~O");709c$.subdomainLoopQuery=$_M(c$,"subdomainLoopQuery",710function(p){711var created=new Date().getTime();712return function(){713var runnable=p.runnable;714if(runnable!=null){715if(runnable.pipeKey!=p.key){716var key=p.key;717with(window.parent){718try{719net.sf.j2s.ajax.SimplePipeHelper.removePipe(key);720net.sf.j2s.ajax.SimplePipeRequest.pipeIFrameClean(key);721return;722}catch(e){723}724}725}726var now=new Date().getTime();727var last=runnable.lastPipeDataReceived;728if(last<=0){729last=created;730}731if((runnable.queryEnded||(now-last>=p.pipeLiveNotifyInterval732&&(p.lastXHR==-1||now-p.lastXHR>=p.pipeLiveNotifyInterval)))733&&runnable.queryFailedRetries<3){734runnable.queryEnded=false;735var method=null;736var url=null;737var data=null;738var key=p.key;739with(window.parent){740try{741method=runnable.getPipeMethod();742url=runnable.getPipeURL();743var spr=net.sf.j2s.ajax.SimplePipeRequest;744data=spr.constructRequest(key,spr.PIPE_TYPE_QUERY);745}catch(e){746}747}748try{749document.domain=p.originalDomain;750}catch(e){};751if(data==null){752with(window.parent){753try{754method=runnable.getPipeMethod();755url=runnable.getPipeURL();756var spr=net.sf.j2s.ajax.SimplePipeRequest;757data=spr.constructRequest(key,spr.PIPE_TYPE_QUERY);758}catch(e){759}760}761}762try{763p.initHttpRequest();764}catch(e){};765var xhrHandle=p.xhrHandle;766try{767with(window.parent){768spr.pipeQueryMap["xhr."+key+"."+data]=xhrHandle;769}770}catch(e){771}772try{773p.pipeXHRQuery(p.xhrHandle,method,url,data);774p.lastXHR=new Date().getTime();775}catch(e){776p.xhrHandle.onreadystatechange=NullObject;777p.xhrHandle=null;778document.domain=p.parentDomain;779runnable.queryEnded=true;780runnable.queryFailedRetries++;781}782}783if(runnable.queryFailedRetries>=3784||now-last>3*p.pipeLiveNotifyInterval){785document.domain=p.parentDomain;786var key=p.key;787with(window.parent){788runnable.pipeAlive=false;789runnable.pipeClosed();790net.sf.j2s.ajax.SimplePipeHelper.removePipe(key);791net.sf.j2s.ajax.SimplePipeRequest.pipeIFrameClean(key);792}793}else{794window.setTimeout(arguments.callee,p.pipeQueryInterval);795}796}797};798},"~O");799c$.checkIFrameSrc=$_M(c$,"checkIFrameSrc",800function(){801try{802var curLoc=""+window.location;803var existed=false;804with(window.parent){805var iframes=document.getElementsByTagName("IFRAME");806for(var i=0;i<iframes.length;i++){807if(iframes[i].src==curLoc){808existed=true;809break;810}811}812}813if(!existed){814var idx=curLoc.indexOf("?");815if(idx!=-1){816var urlPrefix=curLoc.substring(0,idx);817var goalURL=null;818with(window.parent){819var iframes=document.getElementsByTagName("IFRAME");820for(var i=0;i<iframes.length;i++){821if(iframes[i].src.indexOf(urlPrefix)==0){822goalURL=iframes[i].src;823break;824}825}826}827if(goalURL!=null){828window.location.replace(goalURL);829}830}831}832}catch(e){}833$$=$;834$=function(s){835$$(s);836try{837var length=document.body.childNodes.length;838for(var i=length-1;i>=0;i--){839var child=document.body.childNodes[i];840child.parentNode.removeChild(child);841}842}catch(e){}843}844});845c$.$SimplePipeRequest$3$=function(){846$_H();847c$=$_W(net.sf.j2s.ajax,"SimplePipeRequest$3",net.sf.j2s.ajax.XHRCallbackAdapter);848$_V(c$,"onLoaded",849function(){850var responseText=this.f$.request.getResponseText();851if(responseText==null||responseText.length==0){852this.f$.runnable.ajaxFail();853return;854}this.f$.runnable.deserialize(responseText);855this.f$.runnable.ajaxOut();856net.sf.j2s.ajax.SimplePipeRequest.ajaxPipe(this.f$.runnable);857});858c$=$_P();859};860c$.$SimplePipeRequest$4$=function(){861$_H();862c$=$_W(net.sf.j2s.ajax,"SimplePipeRequest$4",net.sf.j2s.ajax.XHRCallbackAdapter);863$_V(c$,"onLoaded",864function(){865{866if(window==null||window["net"]==null)return;867}if(this.f$.pipeRequest.getStatus()!=200){868this.f$.runnable.queryFailedRetries++;869}else{870this.f$.runnable.queryFailedRetries=0;871net.sf.j2s.ajax.SimplePipeRequest.parseReceived(this.f$.pipeRequest.getResponseText());872}this.f$.runnable.queryEnded=true;873{874var pqMap=net.sf.j2s.ajax.SimplePipeRequest.pipeQueryMap;875for(var key in pqMap){876if(typeof key=="string"&&key.indexOf("xhr."+this.f$.runnable.pipeKey+".")==0){877if(pqMap[key]==null||pqMap[key]===this.f$.pipeRequest){878delete pqMap[key];879}else{880delete pqMap[key];881this.f$.runnable.queryEnded=false;882}883}884}885}});886c$=$_P();887};888c$.$SimplePipeRequest$5$=function(){889$_H();890c$=$_W(net.sf.j2s.ajax,"SimplePipeRequest$5",net.sf.j2s.ajax.HttpRequest);891$_V(c$,"initializeReceivingMonitor",892function(){893return this.f$.montior;894});895c$=$_P();896};897$_I(net.sf.j2s.ajax.SimplePipeRequest,"IHttpPipeRequestFactory",net.sf.j2s.ajax.SimpleRPCRequest.IHttpRequestFactory);898$_S(c$,899"PIPE_STATUS_OK","o",900"PIPE_STATUS_DESTROYED","d",901"PIPE_STATUS_CONTINUE","e",902"PIPE_STATUS_LOST","l",903"PIPE_TYPE_QUERY","q",904"PIPE_TYPE_SUBDOMAIN_QUERY","u",905"PIPE_TYPE_NOTIFY","n",906"PIPE_TYPE_SCRIPT","s",907"PIPE_TYPE_XSS","x",908"PIPE_TYPE_CONTINUUM","c",909"FORM_PIPE_KEY","k",910"FORM_PIPE_TYPE","t",911"FORM_PIPE_DOMAIN","d",912"FORM_PIPE_RANDOM","r",913"PIPE_KEY_LENGTH",6,914"MODE_PIPE_QUERY",3,915"MODE_PIPE_CONTINUUM",4,916"pipeMode",4,917"pipeQueryInterval",1000,918"pipeLiveNotifyInterval",25000,919"reqCount",0);920c$.pipeScriptMap=c$.prototype.pipeScriptMap=new JavaObject();921c$.pipeQueryMap=c$.prototype.pipeQueryMap=new JavaObject();922$_S(c$,923"escKeyAbortingDisabled",false);924window["$p1p3p$"]=net.sf.j2s.ajax.SimplePipeRequest.parseReceived;925window["$p1p3b$"]=net.sf.j2s.ajax.SimplePipeRequest.pipeNotifyCallBack;...

Full Screen

Full Screen

extract-runnable-items.test.js

Source:extract-runnable-items.test.js Github

copy

Full Screen

1var expect = require('chai').expect,2 extractRunnableItems = require('../../lib/runner/extract-runnable-items').extractRunnableItems,3 sdk = require('postman-collection'),4 _ = require('lodash');5describe('extractRunnableItems', function () {6 var collection = new sdk.Collection({7 id: 'C1',8 name: 'Collection C1',9 item: [{10 id: 'ID1',11 name: 'F1',12 item: [{13 id: 'ID3',14 name: 'F1.R1',15 request: 'https://postman-echo.com/get'16 }, {17 id: 'ID4',18 name: 'F1.F1',19 item: [{20 id: 'IDx',21 name: 'F1.F1.R1',22 request: 'https://postman-echo.com/cookies'23 }]24 }]25 },26 {27 id: 'ID2',28 name: 'F2',29 item: [{30 name: 'F2.R1',31 request: 'https://postman-echo.com/get'32 }]33 }, {34 id: 'ID6',35 name: 'R1',36 request: 'https://postman-echo.com/get'37 }]38 }),39 collectionWithDuplicates = new sdk.Collection({40 id: 'C2',41 name: 'Collection C2',42 item: [{43 id: 'ID1',44 name: 'R1',45 request: 'https://postman-echo.com/get'46 },47 {48 id: 'ID2',49 name: 'R1',50 request: 'https://postman-echo.com/post'51 }]52 });53 describe('without entrypoint', function () {54 it('should return all items on collection', function (done) {55 extractRunnableItems(collection, null, function (err, runnableItems, entrypoint) {56 expect(err).to.be.null;57 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1', 'F2.R1', 'R1']);58 expect(entrypoint).to.have.property('name', 'Collection C1');59 done();60 });61 });62 });63 describe('invalid entrypoint', function () {64 it('should handle invalid entry points as string', function (done) {65 extractRunnableItems(collection, 'random', function (err, runnableItems, entrypoint) {66 expect(err).to.be.null;67 expect(runnableItems).to.eql([]);68 expect(entrypoint).to.be.undefined;69 done();70 });71 });72 it('should handle invalid lookupStrategy', function (done) {73 extractRunnableItems(collection,74 { execute: 'random', lookupStrategy: 'dealWithIt' },75 function (err, runnableItems, entrypoint) {76 expect(err).to.have.property('message',77 'runtime~extractRunnableItems: Invalid entrypoint lookupStrategy');78 expect(runnableItems).to.be.undefined;79 expect(entrypoint).to.be.undefined;80 done();81 });82 });83 });84 describe('lookupStrategy: path', function () {85 it('should handle invalid entry points', function (done) {86 extractRunnableItems(collection, {87 execute: 'random',88 lookupStrategy: 'path',89 path: ['random_path']90 },91 function (err, runnableItems, entrypoint) {92 expect(err).to.be.null;93 expect(runnableItems).to.eql([]);94 expect(entrypoint).to.be.undefined;95 done();96 });97 });98 it('should match item in top level', function (done) {99 extractRunnableItems(collection,100 { execute: 'ID6', lookupStrategy: 'path' },101 function (err, runnableItems, entrypoint) {102 expect(err).to.be.null;103 expect(_.map(runnableItems, 'name')).to.eql(['R1']);104 expect(entrypoint).to.have.property('name', 'R1');105 done();106 });107 });108 it('should match item in nested level', function (done) {109 extractRunnableItems(collection,110 { execute: 'ID3', lookupStrategy: 'path', path: ['ID1'] },111 function (err, runnableItems, entrypoint) {112 expect(err).to.be.null;113 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1']);114 expect(entrypoint).to.have.property('name', 'F1.R1');115 done();116 });117 });118 it('should match item group at top level', function (done) {119 extractRunnableItems(collection,120 { execute: 'ID1', lookupStrategy: 'path' },121 function (err, runnableItems, entrypoint) {122 expect(err).to.be.null;123 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1']);124 expect(entrypoint).to.have.property('name', 'F1');125 done();126 });127 });128 it('should match item group at nested level', function (done) {129 extractRunnableItems(collection,130 { execute: 'ID4', lookupStrategy: 'path', path: ['ID1'] },131 function (err, runnableItems, entrypoint) {132 expect(err).to.be.null;133 expect(_.map(runnableItems, 'name')).to.eql(['F1.F1.R1']);134 expect(entrypoint).to.have.property('name', 'F1.F1');135 done();136 });137 });138 });139 describe('lookupStrategy: idOrName', function () {140 it('should handle invalid entry points', function (done) {141 extractRunnableItems(collection, {142 execute: 'random',143 lookupStrategy: 'idOrName'144 },145 function (err, runnableItems, entrypoint) {146 expect(err).to.be.null;147 expect(runnableItems).to.eql([]);148 expect(entrypoint).to.be.undefined;149 done();150 });151 });152 it('should be default', function (done) {153 extractRunnableItems(collection,154 { execute: 'ID2' },155 function (err, runnableItems, entrypoint) {156 expect(err).to.be.null;157 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1']);158 expect(entrypoint).to.eql(collection.items.members[1]);159 done();160 });161 });162 it('should filter item group by id', function (done) {163 extractRunnableItems(collection,164 { execute: 'ID2', lookupStrategy: 'idOrName' },165 function (err, runnableItems, entrypoint) {166 expect(err).to.be.null;167 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1']);168 expect(entrypoint).to.eql(collection.items.members[1]);169 done();170 });171 });172 it('should filter item correctly by id', function (done) {173 extractRunnableItems(collection,174 { execute: 'ID3', lookupStrategy: 'idOrName' },175 function (err, runnableItems, entrypoint) {176 expect(err).to.be.null;177 expect(runnableItems).to.have.length(1);178 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1']);179 expect(entrypoint).to.have.property('name', 'F1.R1');180 done();181 });182 });183 it('should filter item group by name', function (done) {184 extractRunnableItems(collection,185 { execute: 'F1', lookupStrategy: 'idOrName' },186 function (err, runnableItems, entrypoint) {187 expect(err).to.be.null;188 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1']);189 expect(entrypoint).to.eql(collection.items.members[0]);190 done();191 });192 });193 it('should filter item correctly by name', function (done) {194 extractRunnableItems(collection,195 { execute: 'F1.R1', lookupStrategy: 'idOrName' },196 function (err, runnableItems, entrypoint) {197 expect(err).to.be.null;198 expect(runnableItems).to.have.length(1);199 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1']);200 expect(entrypoint).to.have.property('name', 'F1.R1');201 done();202 });203 });204 it('should choose the first match in collection order', function (done) {205 extractRunnableItems(collectionWithDuplicates, {206 execute: 'R1',207 lookupStrategy: 'idOrName'208 },209 function (err, runnableItems, entrypoint) {210 expect(err).to.be.null;211 expect(runnableItems).to.have.length(1);212 expect(_.map(runnableItems, 'id')).to.eql(['ID1']);213 expect(entrypoint).to.have.property('name', 'R1');214 done();215 });216 });217 });218 describe('lookupStrategy: multipleIdOrName', function () {219 it('should handle invalid entry points', function (done) {220 extractRunnableItems(collection, {221 execute: 'random',222 lookupStrategy: 'multipleIdOrName'223 },224 function (err, runnableItems, entrypoint) {225 expect(err).to.be.null;226 expect(runnableItems).to.eql([]);227 expect(entrypoint).to.be.undefined;228 done();229 });230 });231 it('should bail out if any of the given entrypoint is not found. ', function (done) {232 extractRunnableItems(collection, {233 execute: ['ID3', 'RANDOM'],234 lookupStrategy: 'multipleIdOrName'235 },236 function (err, runnableItems, entrypoint) {237 expect(err).to.be.null;238 expect(runnableItems).to.eql([]);239 expect(entrypoint).to.be.undefined;240 done();241 });242 });243 it('should filter single item group by id', function (done) {244 extractRunnableItems(collection, {245 execute: ['ID2'],246 lookupStrategy: 'multipleIdOrName'247 },248 function (err, runnableItems, entrypoint) {249 expect(err).to.be.null;250 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1']);251 expect(entrypoint).to.have.property('name', 'Collection C1');252 done();253 });254 });255 it('should filter multiple item groups by id', function (done) {256 extractRunnableItems(collection, {257 execute: ['ID1', 'ID2'],258 lookupStrategy: 'multipleIdOrName'259 },260 function (err, runnableItems, entrypoint) {261 expect(err).to.be.null;262 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1', 'F2.R1']);263 expect(entrypoint).to.have.property('name', 'Collection C1');264 done();265 });266 });267 it('should filter single item by id', function (done) {268 extractRunnableItems(collection, {269 execute: ['ID3'],270 lookupStrategy: 'multipleIdOrName'271 },272 function (err, runnableItems, entrypoint) {273 expect(err).to.be.null;274 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1']);275 expect(entrypoint).to.have.property('name', 'Collection C1');276 done();277 });278 });279 it('should filter multiple items by id', function (done) {280 extractRunnableItems(collection, {281 execute: ['ID3', 'ID4', 'ID6'],282 lookupStrategy: 'multipleIdOrName'283 },284 function (err, runnableItems, entrypoint) {285 expect(err).to.be.null;286 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1', 'R1']);287 expect(entrypoint).to.have.property('name', 'Collection C1');288 done();289 });290 });291 it('should filter single item group by name', function (done) {292 extractRunnableItems(collection, {293 execute: ['F1'],294 lookupStrategy: 'multipleIdOrName'295 },296 function (err, runnableItems, entrypoint) {297 expect(err).to.be.null;298 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1']);299 expect(entrypoint).to.have.property('name', 'Collection C1');300 done();301 });302 });303 it('should filter multiple item groups by name', function (done) {304 extractRunnableItems(collection, {305 execute: ['F1', 'F2'],306 lookupStrategy: 'multipleIdOrName'307 },308 function (err, runnableItems, entrypoint) {309 expect(err).to.be.null;310 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1', 'F2.R1']);311 expect(entrypoint).to.have.property('name', 'Collection C1');312 done();313 });314 });315 it('should filter single item by name', function (done) {316 extractRunnableItems(collection, {317 execute: ['F1.R1'],318 lookupStrategy: 'multipleIdOrName'319 },320 function (err, runnableItems, entrypoint) {321 expect(err).to.be.null;322 expect(runnableItems).to.have.lengthOf(1);323 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1']);324 expect(entrypoint).to.have.property('name', 'Collection C1');325 done();326 });327 });328 it('should filter multiple items by name', function (done) {329 extractRunnableItems(collection, {330 execute: ['F1.R1', 'F2.R1'],331 lookupStrategy: 'multipleIdOrName'332 },333 function (err, runnableItems, entrypoint) {334 expect(err).to.be.null;335 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F2.R1']);336 expect(entrypoint).to.have.property('name', 'Collection C1');337 done();338 });339 });340 it('should filter by combination of id and name', function (done) {341 extractRunnableItems(collection, {342 execute: ['ID1', 'F2'],343 lookupStrategy: 'multipleIdOrName'344 },345 function (err, runnableItems, entrypoint) {346 expect(err).to.be.null;347 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1', 'F2.R1']);348 expect(entrypoint).to.have.property('name', 'Collection C1');349 done();350 });351 });352 it('should follow collection order', function (done) {353 extractRunnableItems(collection, {354 execute: ['ID6', 'ID1', 'ID2'],355 lookupStrategy: 'multipleIdOrName'356 },357 function (err, runnableItems, entrypoint) {358 expect(err).to.be.null;359 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1', 'F2.R1', 'R1']);360 expect(entrypoint).to.have.property('name', 'Collection C1');361 done();362 });363 });364 it('should avoid nested entrypoints', function (done) {365 extractRunnableItems(collection, {366 execute: ['F1', 'F1.F1', 'F1.F1.R1'],367 lookupStrategy: 'multipleIdOrName'368 },369 function (err, runnableItems, entrypoint) {370 expect(err).to.be.null;371 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1']);372 expect(entrypoint).to.have.property('name', 'Collection C1');373 done();374 });375 });376 it('should choose the first match in collection order', function (done) {377 extractRunnableItems(collectionWithDuplicates, {378 execute: ['R1'],379 lookupStrategy: 'multipleIdOrName'380 },381 function (err, runnableItems, entrypoint) {382 expect(err).to.be.null;383 expect(runnableItems).to.have.lengthOf(1);384 expect(_.map(runnableItems, 'id')).to.eql(['ID1']);385 expect(entrypoint).to.have.property('name', 'Collection C2');386 done();387 });388 });389 it('should ignore duplicates in name', function (done) {390 extractRunnableItems(collectionWithDuplicates, {391 execute: ['R1', 'R1'],392 lookupStrategy: 'multipleIdOrName'393 },394 function (err, runnableItems, entrypoint) {395 expect(err).to.be.null;396 expect(runnableItems).to.have.lengthOf(1);397 expect(_.map(runnableItems, 'id')).to.eql(['ID1']);398 expect(entrypoint).to.have.property('name', 'Collection C2');399 done();400 });401 });402 describe('With preserveOrder', function () {403 it('should follow the collection order when unset', function (done) {404 extractRunnableItems(collection, {405 execute: ['ID6', 'ID2'],406 preserveOrder: false,407 lookupStrategy: 'multipleIdOrName'408 },409 function (err, runnableItems) {410 expect(err).to.be.null;411 expect(runnableItems).to.have.length(2);412 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1', 'R1']);413 done();414 });415 });416 it('should follow the order of folders/items in entrypoint when unset', function (done) {417 extractRunnableItems(collection, {418 execute: ['ID6', 'ID2'],419 preserveOrder: true,420 lookupStrategy: 'multipleIdOrName'421 },422 function (err, runnableItems) {423 expect(err).to.be.null;424 expect(runnableItems).to.have.length(2);425 expect(_.map(runnableItems, 'name')).to.eql(['R1', 'F2.R1']);426 done();427 });428 });429 });430 });431 describe('lookupStrategy: followOrder', function () {432 it('should handle invalid entry points', function (done) {433 extractRunnableItems(collection, {434 execute: 'random',435 lookupStrategy: 'followOrder'436 },437 function (err, runnableItems, entrypoint) {438 expect(err).to.be.null;439 expect(runnableItems).to.eql([]);440 expect(entrypoint).to.be.undefined;441 done();442 });443 });444 it('should bail out if any of the given entrypoint is not found. ', function (done) {445 extractRunnableItems(collection, {446 execute: ['ID3', 'RANDOM'],447 lookupStrategy: 'followOrder'448 },449 function (err, runnableItems, entrypoint) {450 expect(err).to.be.null;451 expect(runnableItems).to.eql([]);452 expect(entrypoint).to.be.undefined;453 done();454 });455 });456 it('should filter single item group by id', function (done) {457 extractRunnableItems(collection, {458 execute: ['ID2'],459 lookupStrategy: 'followOrder'460 },461 function (err, runnableItems, entrypoint) {462 expect(err).to.be.null;463 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1']);464 expect(entrypoint).to.have.property('name', 'Collection C1');465 done();466 });467 });468 it('should filter multiple item groups by id and follow the order', function (done) {469 extractRunnableItems(collection, {470 execute: ['ID2', 'ID1'],471 lookupStrategy: 'followOrder'472 },473 function (err, runnableItems, entrypoint) {474 expect(err).to.be.null;475 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1', 'F1.R1', 'F1.F1.R1']);476 expect(entrypoint).to.have.property('name', 'Collection C1');477 done();478 });479 });480 it('should filter single item by id', function (done) {481 extractRunnableItems(collection, {482 execute: ['ID3'],483 lookupStrategy: 'followOrder'484 },485 function (err, runnableItems, entrypoint) {486 expect(err).to.be.null;487 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1']);488 expect(entrypoint).to.have.property('name', 'Collection C1');489 done();490 });491 });492 it('should filter multiple items by id and follow the order', function (done) {493 extractRunnableItems(collection, {494 execute: ['ID3', 'ID6', 'ID4'],495 lookupStrategy: 'followOrder'496 },497 function (err, runnableItems, entrypoint) {498 expect(err).to.be.null;499 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'R1', 'F1.F1.R1']);500 expect(entrypoint).to.have.property('name', 'Collection C1');501 done();502 });503 });504 it('should filter single item group by name', function (done) {505 extractRunnableItems(collection, {506 execute: ['F1'],507 lookupStrategy: 'followOrder'508 },509 function (err, runnableItems, entrypoint) {510 expect(err).to.be.null;511 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1']);512 expect(entrypoint).to.have.property('name', 'Collection C1');513 done();514 });515 });516 it('should filter multiple item groups by name and follow the order', function (done) {517 extractRunnableItems(collection, {518 execute: ['F2', 'F1'],519 lookupStrategy: 'followOrder'520 },521 function (err, runnableItems, entrypoint) {522 expect(err).to.be.null;523 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1', 'F1.R1', 'F1.F1.R1']);524 expect(entrypoint).to.have.property('name', 'Collection C1');525 done();526 });527 });528 it('should filter single item by name', function (done) {529 extractRunnableItems(collection, {530 execute: ['F1.R1'],531 lookupStrategy: 'followOrder'532 },533 function (err, runnableItems, entrypoint) {534 expect(err).to.be.null;535 expect(runnableItems).to.have.lengthOf(1);536 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1']);537 expect(entrypoint).to.have.property('name', 'Collection C1');538 done();539 });540 });541 it('should filter multiple items by name and follow the order', function (done) {542 extractRunnableItems(collection, {543 execute: ['F2.R1', 'F1.R1'],544 lookupStrategy: 'followOrder'545 },546 function (err, runnableItems, entrypoint) {547 expect(err).to.be.null;548 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1', 'F1.R1']);549 expect(entrypoint).to.have.property('name', 'Collection C1');550 done();551 });552 });553 it('should filter by combination of id and name and follow the order', function (done) {554 extractRunnableItems(collection, {555 execute: ['F2', 'ID1'],556 lookupStrategy: 'followOrder'557 },558 function (err, runnableItems, entrypoint) {559 expect(err).to.be.null;560 expect(_.map(runnableItems, 'name')).to.eql(['F2.R1', 'F1.R1', 'F1.F1.R1']);561 expect(entrypoint).to.have.property('name', 'Collection C1');562 done();563 });564 });565 it('should avoid nested entrypoints', function (done) {566 extractRunnableItems(collection, {567 execute: ['F1', 'F1.F1', 'F1.F1.R1'],568 lookupStrategy: 'followOrder'569 },570 function (err, runnableItems, entrypoint) {571 expect(err).to.be.null;572 expect(_.map(runnableItems, 'name')).to.eql(['F1.R1', 'F1.F1.R1']);573 expect(entrypoint).to.have.property('name', 'Collection C1');574 done();575 });576 });577 it('should choose the first match in collection order', function (done) {578 extractRunnableItems(collectionWithDuplicates, {579 execute: ['R1'],580 lookupStrategy: 'followOrder'581 },582 function (err, runnableItems, entrypoint) {583 expect(err).to.be.null;584 expect(runnableItems).to.have.lengthOf(1);585 expect(_.map(runnableItems, 'id')).to.eql(['ID1']);586 expect(entrypoint).to.have.property('name', 'Collection C2');587 done();588 });589 });590 it('should follow the order for duplicates', function (done) {591 extractRunnableItems(collection, {592 execute: ['R1', 'ID4', 'R1'],593 lookupStrategy: 'followOrder'594 },595 function (err, runnableItems, entrypoint) {596 expect(err).to.be.null;597 expect(runnableItems).to.have.lengthOf(3);598 expect(_.map(runnableItems, 'id')).to.eql(['ID6', 'IDx', 'ID6']);599 expect(entrypoint).to.have.property('name', 'Collection C1');600 done();601 });602 });603 });...

Full Screen

Full Screen

runnable.js

Source:runnable.js Github

copy

Full Screen

1/**2 * JS for runnable component3 *4 * IF USED IN BLOG, DO NOT MODIFY - to make it easier to share this logic with5 * the docs website, please write any custom JS elsewhere.6 *7 * Uses JQuery8 */9/********** Cookie helpers **/10function createCookie(name, val, days) {11 var expires = '';12 if (days) {13 var date = new Date();14 date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);15 expires = '; expires=' + date.toUTCString();16 }17 document.cookie = name + '=' + val + expires + '; path=/';18}19function readCookie(name) {20 var nameEQ = name + '=';21 var ca = document.cookie.split(';');22 for (var i = 0; i < ca.length; i++) {23 var c = ca[i];24 while (c.charAt(0) == ' ') c = c.substring(1, c.length);25 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);26 }27 return null;28}29function eraseCookie(name) {30 createCookie(name, '', -1);31}32(function() {33 // Initialize languages34 var preferredLang = readCookie('lang');35 if (preferredLang) {36 $('.runnable').each(function() {37 var $runnable = $(this);38 navToRunnableTab($runnable, preferredLang);39 });40 } else {41 createCookie('lang', 'curl', 365);42 }43 // setupRunnableClipboard configures clipboard buttons for runnable44 // @params runnableEl {HTMLElement|JQueryElement} - HTML Element for runnable45 function setupRunnableClipboard(runnableEl) {46 // Set up clipboard47 var codeClipEl = $(runnableEl).find(48 '.code-btn[data-action="copy-code"]'49 )[0];50 var codeClip = new Clipboard(codeClipEl, {51 text: function(trigger) {52 var $runnable = $(trigger).closest('.runnable');53 var text = $runnable54 .find('.runnable-code .runnable-tab-content.active')55 .text()56 .trim();57 return text.replace(/^\$\s/gm, '');58 },59 });60 codeClip.on('success', function(e) {61 e.clearSelection();62 $(e.trigger)63 .text('Copied')64 .addClass('copied');65 window.setTimeout(function() {66 $(e.trigger)67 .text('Copy')68 .removeClass('copied');69 }, 2000);70 });71 codeClip.on('error', function(e) {72 e.clearSelection();73 $(e.trigger).text('Error copying');74 window.setTimeout(function() {75 $(e.trigger).text('Copy');76 }, 2000);77 });78 var outputClipEl = $(runnableEl).find(79 '.code-btn[data-action="copy-output"]'80 )[0];81 var outputClip = new Clipboard(outputClipEl, {82 text: function(trigger) {83 var $runnable = $(trigger).closest('.runnable');84 var $output = $runnable.find('.output');85 var text = $output.text().trim() || ' ';86 return text;87 },88 });89 outputClip.on('success', function(e) {90 e.clearSelection();91 $(e.trigger)92 .text('Copied')93 .addClass('copied');94 window.setTimeout(function() {95 $(e.trigger)96 .text('Copy')97 .removeClass('copied');98 }, 2000);99 });100 outputClip.on('error', function(e) {101 e.clearSelection();102 $(e.trigger).text('Error copying');103 window.setTimeout(function() {104 $(e.trigger).text('Copy');105 }, 2000);106 });107 }108 /**109 * launchRunnableModal launches a runnable in a modal and configures the110 * clipboard buttons111 *112 * @params runnabelEl {HTMLElement} - a runnable element113 * @params options {Object}114 * @params options.runnableClass {String} - the class name to apply to the115 * '.runnable' div. Useful when launching the runnabe as editing mode.116 */117 function launchRunnableModal(runnabelEl, options) {118 // default argument119 options = typeof options !== 'undefined' ? options : {};120 var $originalRunnable = $(runnabelEl);121 var $modal = $('#runnable-modal');122 var $modalBody = $modal.find('.modal-body');123 // set inner html as runnable124 var str = $originalRunnable.prop('outerHTML');125 $modalBody.html(str);126 // show modal127 $modal.modal({128 keyboard: true,129 });130 var $runnableEl = $modal.find('.runnable');131 if (options.runnableClass) {132 $runnableEl.addClass(options.runnableClass);133 }134 // intiailze clipboard135 setupRunnableClipboard($runnableEl);136 }137 /**138 * navToRunnableTab navigates to the target tab139 * @params targetTab {String}140 */141 function navToRunnableTab($runnable, targetTab) {142 // If needed, exit the edit mode143 if (targetTab !== 'edit' && $runnable.hasClass('editing')) {144 $runnable.removeClass('editing');145 }146 $runnable.find('.nav-languages .language.active').removeClass('active');147 $runnable148 .find('.language[data-target="' + targetTab + '"]')149 .addClass('active');150 $runnable.find('.runnable-tab-content.active').removeClass('active');151 $runnable152 .find('.runnable-tab-content[data-tab="' + targetTab + '"]')153 .addClass('active');154 }155 // changeLanguage changes the preferred programminng language for the examples156 // and navigate all example tabs to that language157 // @params language {String}158 function changeLanguage(language) {159 // First, set cookie160 createCookie('lang', language, 365);161 // Navigate all runnable tabs to the langauge162 $('.runnable').each(function() {163 var $runnable = $(this);164 navToRunnableTab($runnable, language);165 });166 }167 function initCodeMirror($runnable) {168 $runnable.find('.CodeMirror').remove();169 var editableEl = $runnable.find('.query-content-editable')[0];170 var cm = CodeMirror.fromTextArea(editableEl, {171 lineNumbers: true,172 autoCloseBrackets: true,173 lineWrapping: true,174 autofocus: true,175 tabSize: 2,176 });177 cm.on('change', function(c) {178 var val = c.doc.getValue();179 $runnable.attr('data-unsaved', val);180 c.save();181 });182 }183 // updateQueryContents updates the query contents in all tabs184 function updateQueryContents($runnables, newQuery) {185 var cleanValue = newQuery.trim().replace(/\n$/g, '');186 $runnables.find('.query-content').text(cleanValue);187 }188 function getLatencyTooltipHTML(serverLatencyInfo, networkLatency) {189 var contentHTML =190 '<div class="measurement-row"><div class="measurement-key">JSON:</div><div class="measurement-val">' +191 prettifyLatency(serverLatencyInfo.encoding_ns) +192 '</div></div><div class="measurement-row"><div class="measurement-key">Parsing:</div><div class="measurement-val">' +193 prettifyLatency(serverLatencyInfo.parsing_ns) +194 '</div></div><div class="measurement-row"><div class="measurement-key">Processing:</div><div class="measurement-val">' +195 prettifyLatency(serverLatencyInfo.processing_ns) +196 '</div></div><div class="divider"></div><div class="measurement-row"><div class="measurement-key total">Total:</div><div class="measurement-val">' +197 serverLatencyInfo.total +198 '</div></div>';199 var outputHTML =200 '<div class="latency-tooltip-container">' + contentHTML + '</div>';201 return outputHTML;202 }203 function getTotalServerLatencyInMS(serverLatencyInfo) {204 var totalLatency = 0;205 // Server returns parsing, processing and encoding latencies in ns separately.206 for (var latency in serverLatencyInfo) {207 totalLatency += parseFloat(serverLatencyInfo[latency]);208 }209 return totalLatency;210 }211 function prettifyLatency(latency) {212 // Convert from ns to ms213 latency = latency / Math.pow(10, 6);214 var serverLatency;215 if (latency < 1) {216 serverLatency = Math.round(latency * 1000) + 'μs';217 } else if (latency > 1000) {218 serverLatency = Math.round(latency / 1000) + 's';219 } else {220 serverLatency = Math.round(latency) + 'ms';221 }222 return serverLatency;223 }224 /**225 * updateLatencyInformation update the latency information displayed in the226 * $runnable.227 *228 * @params $runnable {JQueryElement}229 * @params serverLatencyInfo {Object} - latency info returned by the server230 * @params networkLatency {Number} - network latency in milliseconds231 */232 function updateLatencyInformation(233 $runnable,234 serverLatencyInfo,235 networkLatency236 ) {237 var isModal = $runnable.parents('#runnable-modal').length > 0;238 var totalServerLatency = getTotalServerLatencyInMS(serverLatencyInfo);239 var networkOnlyLatency = Math.round(240 networkLatency - totalServerLatency / Math.pow(10, 6)241 );242 serverLatency = prettifyLatency(totalServerLatency);243 serverLatencyInfo.total = serverLatency;244 $runnable.find('.latency-info').removeClass('hidden');245 $runnable.find('.server-latency .number').text(serverLatency);246 $runnable.find('.network-latency .number').text(networkOnlyLatency + 'ms');247 var tooltipHTML = getLatencyTooltipHTML(248 serverLatencyInfo,249 networkOnlyLatency250 );251 $runnable252 .find('.server-latency-tooltip-trigger')253 .attr('title', tooltipHTML)254 .tooltip();255 }256 /**257 * hasQueryChanged returns true if the query being executed has been edited by258 * the user.259 *260 * @params $runnable {JQueryElement}261 */262 function hasQueryChanged(runnable) {263 var current = $(runnable).attr('data-current');264 var initial = $(runnable).data('initial');265 return current !== initial;266 }267 // Running code268 $(document).on('click', '.runnable [data-action="run"]', function(e) {269 e.preventDefault();270 // there can be at most two instances of a same runnable because users can271 // launch a runnable as a modal. they share the same checksum272 var checksum = $(this)273 .closest('.runnable')274 .data('checksum');275 var $currentRunnable = $(this).closest('.runnable');276 var $runnables = $('.runnable[data-checksum="' + checksum + '"]');277 var codeEl = $runnables.find('.output');278 var isModal = $currentRunnable.parents('#runnable-modal').length > 0;279 var query = $(this)280 .closest('.runnable')281 .attr('data-current');282 var vars = $(this)283 .closest('.runnable')284 .attr('data-vars');285 // Get current endpoint value.286 var endpoint = $(this)287 .closest('.runnable')288 .find('#endpoint')289 .val();290 $runnables.find('.output-container').removeClass('empty error');291 codeEl.text('Waiting for the server response...');292 var startTime;293 $.post({294 // Use entered endpoint attr if applicable, otherwise use default (global) endpoint.295 url: endpoint ? endpoint : window.DGRAPH_ENDPOINT,296 headers: {297 'X-Dgraph-Vars': vars,298 },299 data: query,300 dataType: 'json',301 beforeSend: function() {302 startTime = new Date().getTime();303 },304 })305 .done(function(res) {306 var now = new Date().getTime();307 var networkLatency = now - startTime;308 var serverLatencyInfo = res.extensions && res.extensions.server_latency;309 delete res.extensions;310 // In some cases, the server does not return latency information311 // TODO: Remove special handling from next version as Dgraph would312 // return 400 status code in case of error.313 if ((!res.code || !/Error/i.test(res.code)) && serverLatencyInfo) {314 updateLatencyInformation(315 $runnables,316 serverLatencyInfo,317 networkLatency318 );319 }320 // If its the default query and we did not get any results, that means321 // data was not loaded properly.322 if (!hasQueryChanged($currentRunnable) && $.isEmptyObject(res)) {323 Raven.captureMessage('No result returned for default query', {324 extra: {325 query: query,326 },327 });328 }329 var userOutput = JSON.stringify(res, null, 2);330 codeEl.text(userOutput);331 for (var i = 0; i < codeEl.length; i++) {332 hljs.highlightBlock(codeEl[i]);333 }334 if (!isModal) {335 var currentRunnableEl = $currentRunnable[0];336 launchRunnableModal(currentRunnableEl);337 }338 })339 .fail(function(xhr, status, error) {340 $runnables.find('.output-container').addClass('error');341 var errorText = xhr.responseText || error;342 codeEl.text(errorText);343 // If Dgraph returned an error on a default query that means we forgot344 // to update the Docs. Lets capture it.345 if (!hasQueryChanged($currentRunnable)) {346 Raven.captureMessage('Error while running default query', {347 extra: {348 query: query,349 error: errorText,350 },351 });352 }353 });354 });355 // Refresh code356 $(document).on('click', '.runnable [data-action="reset"]', function(e) {357 e.preventDefault();358 var $runnable = $(this).closest('.runnable');359 var initialQuery = $runnable.data('initial');360 $runnable.attr('data-unsaved', initialQuery);361 $runnable362 .find('.query-content-editable')363 .val(initialQuery)364 .text(initialQuery);365 initCodeMirror($runnable);366 window.setTimeout(function() {367 $runnable.find('.query-content-editable').text(initialQuery);368 }, 80);369 });370 $(document).on('click', '.runnable [data-action="save"]', function(e) {371 e.preventDefault();372 var checksum = $(this)373 .closest('.runnable')374 .data('checksum');375 var $currentRunnable = $(this).closest('.runnable');376 var $runnables = $('.runnable[data-checksum="' + checksum + '"]');377 var newQuery =378 $currentRunnable.attr('data-unsaved') ||379 $currentRunnable.attr('data-current');380 newQuery = newQuery.trim();381 // Update query examples and the textarea with the current query382 $runnables.attr('data-current', newQuery);383 updateQueryContents($runnables, newQuery);384 // We update the value as well as the inner text because when launched in385 // a modal, value will be lose as HTML is copied386 // TODO: implement JS object for runnable instead of storing these states387 // in DOM. Is there a good way to do so without framework?388 $runnables389 .find('.query-content-editable')390 .val(newQuery)391 .text(newQuery);392 var dest = readCookie('lang');393 navToRunnableTab($currentRunnable, dest);394 });395 $(document).on('click', '.runnable [data-action="discard"]', function(e) {396 e.preventDefault();397 var $runnable = $(this).closest('.runnable');398 // Restore to initial query399 var currentQuery = $runnable.attr('data-current');400 updateQueryContents($runnable, currentQuery);401 $runnable402 .find('.query-content-editable')403 .val(currentQuery)404 .text(currentQuery);405 var dest = readCookie('lang');406 navToRunnableTab($runnable, dest);407 });408 $(document).on('click', '.runnable [data-action="expand"]', function(e) {409 e.preventDefault();410 var $runnable = $(this).closest('.runnable');411 var runnableEl = $runnable[0];412 launchRunnableModal(runnableEl);413 });414 $(document).on('click', '.runnable [data-action="edit"]', function(e) {415 e.preventDefault();416 var $runnable = $(this).closest('.runnable');417 var isModal = $runnable.parents('#runnable-modal').length > 0;418 if (isModal) {419 $runnable.addClass('editing');420 navToRunnableTab($runnable, 'edit');421 initCodeMirror($runnable);422 } else {423 var currentRunnableEl = $runnable;424 launchRunnableModal(currentRunnableEl, {425 runnableClass: 'editing',426 });427 }428 });429 $(document).on('click', '.runnable [data-action="nav-lang"]', function(e) {430 e.preventDefault();431 var targetTab = $(this).data('target');432 var $runnable = $(this).closest('.runnable');433 changeLanguage(targetTab);434 });435 // Runnable modal event hooks436 $('#runnable-modal').on('hidden.bs.modal', function(e) {437 $(this)438 .find('.server-latency-tooltip-trigger')439 .tooltip('dispose');440 $(this)441 .find('.modal-body')442 .html('');443 });444 $('#runnable-modal').on('shown.bs.modal', function() {445 var $runnable = $(this).find('.runnable');446 // Focus the output so that it is scrollable by keyboard447 var $output = $(this).find('.output');448 $output.focus();449 // if .editing class is found on .runnable, we transition to the edit tab450 // and initialize the code mirror. Such transition and initialization should451 // be done when the modal has been completely transitioned, and therefore452 // we put this logic here instead of in launchRunnableModal function at the453 // cost of some added complexity454 var isEditing = $runnable.hasClass('editing');455 if (isEditing) {456 navToRunnableTab($runnable, 'edit');457 initCodeMirror($runnable);458 }459 var hasRun = !$runnable.find('.latency-info').hasClass('hidden');460 if (hasRun) {461 $runnable.find('.server-latency-tooltip-trigger').tooltip();462 }463 });464 /********** On page load **/465 // Initialize runnables466 $('.runnable').each(function() {467 // First, we reinitialize the query contents because some languages require468 // specific formatting469 var $runnable = $(this);470 var currentQuery = $runnable.attr('data-current');471 updateQueryContents($runnable, currentQuery);472 setupRunnableClipboard(this);473 });474 /********** Config **/475 // Get clipboard.js to work inside bootstrap modal476 // http://stackoverflow.com/questions/38398070/bootstrap-modal-does-not-work-with-clipboard-js-on-firefox477 $.fn.modal.Constructor.prototype._enforceFocus = function() {};...

Full Screen

Full Screen

execution-thread.js

Source:execution-thread.js Github

copy

Full Screen

1'use strict';2const _ = require('lodash');3const Promise = require('bluebird');4const ExecutionThread = require('lib/worker/runner/test-runner/execution-thread');5const OneTimeScreenshooter = require('lib/worker/runner/test-runner/one-time-screenshooter');6const {Suite, Test, Runnable} = require('../../../_mocha');7describe('worker/runner/test-runner/execution-thread', () => {8 const sandbox = sinon.sandbox.create();9 const mkTest_ = (opts = {}) => {10 opts.fn = opts.fn || sinon.spy();11 return Test.create(Suite.create(), opts);12 };13 const mkRunnable_ = (opts = {}) => {14 opts.type = opts.type || 'default-runnable-type';15 opts.fn = opts.fn || sinon.spy();16 return Runnable.create(Suite.create(), opts);17 };18 const mkTimedoutRunnable_ = () => {19 const runnable = mkRunnable_({20 type: 'test',21 title: 'bla bla',22 fn: () => Promise.delay(20)23 });24 runnable.timeout(10);25 return runnable;26 };27 const mkBrowser_ = (config = {}) => {28 return {29 config,30 publicAPI: Object.create({31 getCommandHistory: sinon.stub().resolves([])32 })33 };34 };35 const mkExecutionThread_ = (opts = {}) => {36 const test = opts.test || mkTest_();37 const browser = opts.browser || mkBrowser_();38 const hermioneCtx = opts.hermioneCtx || {};39 const screenshooter = opts.screenshooter || Object.create(OneTimeScreenshooter.prototype);40 return ExecutionThread.create({test, browser, hermioneCtx, screenshooter});41 };42 beforeEach(() => {43 sandbox.stub(OneTimeScreenshooter.prototype, 'extendWithPageScreenshot').callsFake((e) => Promise.resolve(e));44 });45 afterEach(() => sandbox.restore());46 describe('run', () => {47 it('should reject on runnable reject', async () => {48 const runnable = mkRunnable_({49 fn: () => Promise.reject(new Error('foo'))50 });51 const executionThread = mkExecutionThread_();52 await assert.isRejected(executionThread.run(runnable), /foo/);53 });54 it('should set browser public API to runnable fn context', async () => {55 const browser = mkBrowser_();56 const runnable = mkRunnable_();57 await mkExecutionThread_({browser}).run(runnable);58 assert.calledOn(runnable.fn, sinon.match({browser: browser.publicAPI}));59 });60 it('should run all runnables on the same context', async () => {61 const firstRunnable = mkRunnable_();62 const secondRunnable = mkRunnable_();63 const executionThread = mkExecutionThread_();64 await executionThread.run(firstRunnable);65 await executionThread.run(secondRunnable);66 assert.equal(67 firstRunnable.fn.firstCall.thisValue,68 secondRunnable.fn.firstCall.thisValue69 );70 });71 it('should set current test to runnable fn context', async () => {72 const test = mkTest_({title: 'some test'});73 const executionThread = mkExecutionThread_({test});74 const runnable = mkRunnable_();75 await executionThread.run(runnable);76 assert.calledOn(runnable.fn, sinon.match({currentTest: {title: 'some test'}}));77 });78 it('should store error in current test on runnable reject', async () => {79 const test = mkTest_();80 const runnable = mkRunnable_({81 fn: () => Promise.reject(new Error('foo'))82 });83 const e = await mkExecutionThread_({test}).run(runnable).catch((e) => e);84 assert.equal(test.err, e);85 });86 it('should not override error in current test on runnable reject', async () => {87 const origError = new Error('bar');88 const test = mkTest_({err: origError});89 const runnable = mkRunnable_({90 fn: () => Promise.reject(new Error('foo'))91 });92 await mkExecutionThread_({test}).run(runnable).catch((e) => e);93 assert.equal(test.err, origError);94 });95 it('should set runnable as browser execution context', async () => {96 let executionContext;97 const runnable = mkRunnable_({98 title: 'some hook',99 fn: function() {100 executionContext = this.browser.executionContext;101 }102 });103 await mkExecutionThread_().run(runnable);104 assert.propertyVal(executionContext, 'title', 'some hook');105 });106 it('should set runnable ctx to browser execution context', async () => {107 let _this;108 let executionContext;109 const runnable = mkRunnable_({110 fn: function() {111 _this = this;112 executionContext = this.browser.executionContext;113 }114 });115 await mkExecutionThread_().run(runnable);116 assert.propertyVal(executionContext, 'ctx', _this);117 });118 it('should share hermioneCtx in browser execution context between all runnables', async () => {119 const hermioneCtx = {};120 const executionThread = mkExecutionThread_({hermioneCtx});121 await executionThread.run(mkRunnable_({122 fn: function() {123 this.browser.executionContext.hermioneCtx.foo = 'bar';124 }125 }));126 await executionThread.run(mkRunnable_({127 fn: function() {128 this.browser.executionContext.hermioneCtx.baz = 'qux';129 }130 }));131 assert.deepEqual(hermioneCtx, {foo: 'bar', baz: 'qux'});132 });133 it('should fail with timeout error on timeout', async () => {134 const runnable = mkTimedoutRunnable_();135 const executionThread = mkExecutionThread_();136 await assert.isRejected(executionThread.run(runnable), /test '.* bla bla' timed out/);137 });138 it('should not set timeout if timeouts are disabled', async () => {139 const runnable = mkRunnable_({140 type: 'test',141 fn: () => Promise.delay(20)142 });143 runnable.timeout(0);144 const executionThread = mkExecutionThread_();145 await assert.isFulfilled(executionThread.run(runnable));146 });147 describe('screenshotOnReject', () => {148 it('should extend error with page screenshot', async () => {149 const error = new Error();150 const runnable = mkRunnable_({151 fn: () => Promise.reject(error)152 });153 OneTimeScreenshooter.prototype.extendWithPageScreenshot154 .withArgs(error).callsFake((e) => {155 return Promise.resolve(_.extend(e, {screenshot: 'base64img'}));156 });157 const err = await mkExecutionThread_().run(runnable)158 .catch((e) => e);159 assert.propertyVal(err, 'screenshot', 'base64img');160 });161 it('should wait until screenshot will be taken', async () => {162 const afterScreenshot = sinon.spy().named('afterScreenshot');163 OneTimeScreenshooter.prototype.extendWithPageScreenshot164 .callsFake(() => Promise.delay(10).then(afterScreenshot));165 const runnable = mkRunnable_({166 fn: () => Promise.reject(new Error())167 });168 await mkExecutionThread_().run(runnable).catch(() => {});169 assert.calledOnce(afterScreenshot);170 });171 it('runnable should not fail with timeout while taking screenshot', async () => {172 const runnable = mkRunnable_({173 fn: () => Promise.reject(new Error('foo'))174 });175 runnable.timeout(10);176 OneTimeScreenshooter.prototype.extendWithPageScreenshot177 .callsFake(() => Promise.delay(20));178 const executionThread = mkExecutionThread_();179 await assert.isRejected(executionThread.run(runnable), /foo/);180 });181 });182 });...

Full Screen

Full Screen

runnable_8hpp.js

Source:runnable_8hpp.js Github

copy

Full Screen

1var runnable_8hpp =2[3 [ "RunnableType", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8ef", [4 [ "kInvalidType", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa07e04ca5d30c4ae7ab7ec939356e60c1", null ],5 [ "kOpenDocument", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa3f1942f11d481fd8b4ebe60609a5871c", null ],6 [ "kCloseDocument", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa0487363149f312ad20b3fa720007a8ae", null ],7 [ "kSetDocState", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efadb84ee8e06398931e44675e129713405", null ],8 [ "kFindText", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efaa49a0f56939bcebfde59b27ebb52840b", null ],9 [ "kPaintSearchSnippet", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efadcc8bb74684261a6a0a547111af50413", null ],10 [ "kPaintCommentSnippet", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa8636ba88762633b067c373106d4f11db", null ],11 [ "kFetchCommentsList", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efaf81f3d9ec184eec22edfd6525ebbef65", null ],12 [ "kPaint", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa3ca5c4cd5f5d32716a3434fff3dc1253", null ],13 [ "kPaintThumbnail", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa4b35c229d31a875be127cc9018423f04", null ],14 [ "kPaintOverlay", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efac8736935e60e3797a65903c07eea7c9d", null ],15 [ "kPreCache", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa748d9614307690b8964a94a1772f9ab6", null ],16 [ "kFetchBookmarks", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa13d561d1e906142f0c93f6df4bceb649", null ],17 [ "kExtractPortfolioFile", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efade88576060c2f2d089df79d09e48c4d5", null ],18 [ "kSelectText", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa7bf2c371f4ff5507bd9524f14e8abb9a", null ],19 [ "kSelectTextViaGrabber", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa38680360f5d6dfe00ac7d447a57d23b4", null ],20 [ "kStructureEnumeration", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa9f007533834feb07ee08cd5ce2ee81d3", null ],21 [ "kUpdateDocumentAnalytics", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa0bcc36732455a2e4b4a9dc2ccd435c09", null ],22 [ "kTrackDocumentOpenAnalytics", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efaedb9e86bdac448136b089ee1546f2933", null ],23 [ "kTrackDocumentCloseAnalytics", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa79730ceb43ec9b64e58a96cdac43a3f0", null ],24 [ "kDocClassifier", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa50d31cbfaeb0190750c8282ab228a20f", null ],25 [ "kDocQualifier", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa2195c30e6e34c9d610bfa2a2b42cd8b3", null ],26 [ "kEraserFetchComments", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efaeec2be3a97276cb0c1a255e361cc3175", null ],27 [ "kDocUnprotect", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efa7086bd376ac12924f1cb88ded97f9e10", null ],28 [ "kDocHasComment", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efac2f24b9f0956e9cef086a434e59a6935", null ],29 [ "kParagraphDetection", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efafc0651f4f72046cb47d92bb638556bd4", null ],30 [ "kCannotCancel", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efac16d9fd19eccc6f8df11596d2828c3d9", null ],31 [ "kCancel", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efaf4b56d94956de9fa8260590ed56e5ad3", null ],32 [ "kRunnableCount", "runnable_8hpp.html#a3466351c5a57ff0dbf48b2282f0bb8efafddd4dd3b013c2441f5d6840a115c31c", null ]33 ] ]...

Full Screen

Full Screen

SafeRunnable.js

Source:SafeRunnable.js Github

copy

Full Screen

1Clazz.declarePackage ("org.eclipse.jface.util");2Clazz.load (["org.eclipse.core.runtime.ISafeRunnable"], "org.eclipse.jface.util.SafeRunnable", ["org.eclipse.jface.dialogs.MessageDialog", "org.eclipse.jface.resource.JFaceResources", "org.eclipse.jface.util.ISafeRunnableRunner"], function () {3c$ = Clazz.decorateAsClass (function () {4this.message = null;5Clazz.instantialize (this, arguments);6}, org.eclipse.jface.util, "SafeRunnable", null, org.eclipse.core.runtime.ISafeRunnable);7Clazz.makeConstructor (c$, 8function () {9});10Clazz.makeConstructor (c$, 11function (message) {12this.message = message;13}, "~S");14Clazz.defineMethod (c$, "handleException", 15function (e) {16if (!org.eclipse.jface.util.SafeRunnable.ignoreErrors) {17if (this.message == null) this.message = org.eclipse.jface.resource.JFaceResources.getString ("SafeRunnable.errorMessage");18org.eclipse.jface.dialogs.MessageDialog.openError (null, org.eclipse.jface.resource.JFaceResources.getString ("Error"), this.message);19}}, "Throwable");20c$.getIgnoreErrors = Clazz.defineMethod (c$, "getIgnoreErrors", 21function (flag) {22return org.eclipse.jface.util.SafeRunnable.ignoreErrors;23}, "~B");24c$.getIgnoreErrors = Clazz.defineMethod (c$, "getIgnoreErrors", 25function () {26return org.eclipse.jface.util.SafeRunnable.ignoreErrors;27});28c$.setIgnoreErrors = Clazz.defineMethod (c$, "setIgnoreErrors", 29function (flag) {30($t$ = org.eclipse.jface.util.SafeRunnable.ignoreErrors = flag, org.eclipse.jface.util.SafeRunnable.prototype.ignoreErrors = org.eclipse.jface.util.SafeRunnable.ignoreErrors, $t$);31}, "~B");32c$.getRunner = Clazz.defineMethod (c$, "getRunner", 33function () {34if (org.eclipse.jface.util.SafeRunnable.runner == null) {35($t$ = org.eclipse.jface.util.SafeRunnable.runner = org.eclipse.jface.util.SafeRunnable.createDefaultRunner (), org.eclipse.jface.util.SafeRunnable.prototype.runner = org.eclipse.jface.util.SafeRunnable.runner, $t$);36}return org.eclipse.jface.util.SafeRunnable.runner;37});38c$.createDefaultRunner = Clazz.defineMethod (c$, "createDefaultRunner", 39($fz = function () {40return ((Clazz.isClassDefined ("org.eclipse.jface.util.SafeRunnable$1") ? 0 : org.eclipse.jface.util.SafeRunnable.$SafeRunnable$1$ ()), Clazz.innerTypeInstance (org.eclipse.jface.util.SafeRunnable$1, this, null));41}, $fz.isPrivate = true, $fz));42c$.setRunner = Clazz.defineMethod (c$, "setRunner", 43function (runner) {44($t$ = org.eclipse.jface.util.SafeRunnable.runner = runner, org.eclipse.jface.util.SafeRunnable.prototype.runner = org.eclipse.jface.util.SafeRunnable.runner, $t$);45}, "org.eclipse.jface.util.ISafeRunnableRunner");46c$.run = Clazz.defineMethod (c$, "run", 47function (runnable) {48org.eclipse.jface.util.SafeRunnable.getRunner ().run (runnable);49}, "org.eclipse.core.runtime.ISafeRunnable");50c$.$SafeRunnable$1$ = function () {51Clazz.pu$h ();52c$ = Clazz.declareAnonymous (org.eclipse.jface.util, "SafeRunnable$1", null, org.eclipse.jface.util.ISafeRunnableRunner);53Clazz.defineMethod (c$, "run", 54function (code) {55try {56code.run ();57} catch (e$$) {58if (Clazz.instanceOf (e$$, Exception)) {59var e = e$$;60{61this.handleException (code, e);62}63} else if (Clazz.instanceOf (e$$, LinkageError)) {64var e = e$$;65{66this.handleException (code, e);67}68} else {69throw e$$;70}71}72}, "org.eclipse.core.runtime.ISafeRunnable");73Clazz.defineMethod (c$, "handleException", 74($fz = function (code, e) {75if (!(Clazz.instanceOf (e, org.eclipse.core.runtime.OperationCanceledException))) {76e.printStackTrace ();77}code.handleException (e);78}, $fz.isPrivate = true, $fz), "org.eclipse.core.runtime.ISafeRunnable,Throwable");79c$ = Clazz.p0p ();80};81Clazz.defineStatics (c$,82"ignoreErrors", false,83"runner", null);...

Full Screen

Full Screen

AWindowDelegate.js

Source:AWindowDelegate.js Github

copy

Full Screen

1$_J("net.sf.j2s.ajax");2$_L(null,"net.sf.j2s.ajax.AWindowDelegate",["$wt.events.DisposeListener","$wt.widgets.Display"],function(){3c$=$_C(function(){4this.win=null;5$_Z(this,arguments);6},net.sf.j2s.ajax,"AWindowDelegate");7$_K(c$,8function(win){9this.win=win;10},"org.eclipse.jface.window.Window");11c$.open=$_M(c$,"open",12function(win,runnable){13win.setBlockOnOpen(false);14new net.sf.j2s.ajax.AWindowDelegate(win).nonBlockOpen(null,runnable);15},"org.eclipse.jface.window.Window,net.sf.j2s.ajax.AWindowRunnable");16c$.asyncOpen=$_M(c$,"asyncOpen",17function(win,oThis,runnable){18win.setBlockOnOpen(false);19new net.sf.j2s.ajax.AWindowDelegate(win).nonBlockOpen(oThis,runnable);20},"org.eclipse.jface.window.Window,~O,net.sf.j2s.ajax.AWindowRunnable");21$_M(c$,"nonBlockOpen",22function(oThis,runnable){23if($_O(runnable,net.sf.j2s.ajax.AWindowRunnable)){24runnable.setWindow(this.win);25}var isJ2SEnv=false;26{27isJ2SEnv=true;28}if(isJ2SEnv){29{30this.win.open();31}((($_D("net.sf.j2s.ajax.AWindowDelegate$1")?0:net.sf.j2s.ajax.AWindowDelegate.$AWindowDelegate$1$()),$_N(net.sf.j2s.ajax.AWindowDelegate$1,this,$_F("oThis",oThis,"runnable",runnable)))).run();32}else{33}},"~O,net.sf.j2s.ajax.AWindowRunnable");34$_M(c$,"getActiveDisplay",35function(){36var display=null;37var shell=this.win.getShell();38if(shell!=null){39display=shell.getDisplay();40}if(display==null){41display=$wt.widgets.Display.getCurrent();42}if(display==null){43display=$wt.widgets.Display.getDefault();44}return display;45});46c$.$AWindowDelegate$1$=function(){47$_H();48c$=$_W(net.sf.j2s.ajax,"AWindowDelegate$1",null,Runnable);49$_M(c$,"run",50function(){51var shell=this.b$["net.sf.j2s.ajax.AWindowDelegate"].win.getShell();52if(shell==null){53this.b$["net.sf.j2s.ajax.AWindowDelegate"].getActiveDisplay().timerExec(10,this);54return;55}shell.addDisposeListener((($_D("net.sf.j2s.ajax.AWindowDelegate$1$1")?0:net.sf.j2s.ajax.AWindowDelegate.$AWindowDelegate$1$1$()),$_N(net.sf.j2s.ajax.AWindowDelegate$1$1,this,$_F("oThis",this.f$.oThis,"runnable",this.f$.runnable))));56shell.getDisplay().readAndDispatch();57});58c$=$_P();59};60c$.$AWindowDelegate$1$1$=function(){61$_H();62c$=$_W(net.sf.j2s.ajax,"AWindowDelegate$1$1",null,$wt.events.DisposeListener);63$_V(c$,"widgetDisposed",64function(e){65e.display.update();66if(this.f$.oThis==null){67e.display.timerExec(5,this.f$.runnable);68}else{69var $runnable=this.f$.runnable;70var $oThis=this.f$.oThis;71window.setTimeout(function(){72$runnable.apply($oThis);73},0);74}},"$wt.events.DisposeEvent");75c$=$_P();76};...

Full Screen

Full Screen

context.js

Source:context.js Github

copy

Full Screen

1'use strict';2/**3 * Module dependencies.4 */5var JSON = require('json3');6/**7 * Expose `Context`.8 */9module.exports = Context;10/**11 * Initialize a new `Context`.12 *13 * @api private14 */15function Context () {}16/**17 * Set or get the context `Runnable` to `runnable`.18 *19 * @api private20 * @param {Runnable} runnable21 * @return {Context}22 */23Context.prototype.runnable = function (runnable) {24 if (!arguments.length) {25 return this._runnable;26 }27 this.test = this._runnable = runnable;28 return this;29};30/**31 * Set test timeout `ms`.32 *33 * @api private34 * @param {number} ms35 * @return {Context} self36 */37Context.prototype.timeout = function (ms) {38 if (!arguments.length) {39 return this.runnable().timeout();40 }41 this.runnable().timeout(ms);42 return this;43};44/**45 * Set test timeout `enabled`.46 *47 * @api private48 * @param {boolean} enabled49 * @return {Context} self50 */51Context.prototype.enableTimeouts = function (enabled) {52 this.runnable().enableTimeouts(enabled);53 return this;54};55/**56 * Set test slowness threshold `ms`.57 *58 * @api private59 * @param {number} ms60 * @return {Context} self61 */62Context.prototype.slow = function (ms) {63 this.runnable().slow(ms);64 return this;65};66/**67 * Mark a test as skipped.68 *69 * @api private70 * @return {Context} self71 */72Context.prototype.skip = function () {73 this.runnable().skip();74 return this;75};76/**77 * Allow a number of retries on failed tests78 *79 * @api private80 * @param {number} n81 * @return {Context} self82 */83Context.prototype.retries = function (n) {84 if (!arguments.length) {85 return this.runnable().retries();86 }87 this.runnable().retries(n);88 return this;89};90/**91 * Inspect the context void of `._runnable`.92 *93 * @api private94 * @return {string}95 */96Context.prototype.inspect = function () {97 return JSON.stringify(this, function (key, val) {98 return key === 'runnable' || key === 'test' ? undefined : val;99 }, 2);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const assert = require('assert');2describe('Array', function() {3 describe('#indexOf()', function() {4 it('should return -1 when the value is not present', function() {5 assert.equal([1,2,3].indexOf(4), -1);6 });7 });8});9const assert = require('assert');10describe('Array', function() {11 describe('#indexOf()', function() {12 it('should return -1 when the value is not present', function() {13 assert.equal([1,2,3].indexOf(4), -1);14 });15 });16});17const assert = require('assert');18suite('Array', function() {19 suite('#indexOf()', function() {20 test('should return -1 when the value is not present', function() {21 assert.equal([1,2,3].indexOf(4), -1);22 });23 });24});25const assert = require('assert');26describe('Array', function() {27 describe('#indexOf()', function() {28 it('should return -1 when the value is not present', function(done) {29 setTimeout(function() {30 assert.equal([1,2,3].indexOf(4), -1);31 done();32 }, 100);33 });34 });35});36const assert = require('assert');37describe('Array', function() {38 before(function() {

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2describe('Array', function() {3 describe('#indexOf()', function () {4 it('should return -1 when the value is not present', function () {5 assert.equal(-1, [1,2,3].indexOf(4));6 });7 });8});9 #indexOf()101 passing (7ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('should return -1 when the value is not present', function() {3 assert.equal(-1, [1,2,3].indexOf(5));4 assert.equal(-1, [1,2,3].indexOf(0));5 });6});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("String#split", function() {2 it("should return an array", function() {3 assert(Array.isArray("a,b,c".split(",")));4 });5});6describe("String#split", function() {7 it("should return an array", function() {8 return "a,b,c".split(",");9 });10});11describe("String#split", function() {12 it("should return an array", function(done) {13 "a,b,c".split(",");14 done();15 });16});17describe("String#split", function() {18 it("should return an array", async function() {19 await "a,b,c".split(",");20 });21});22describe("String#split", function() {23 it("should return an array", async function() {24 await "a,b,c".split(",");25 });26});27describe("String#split", function() {28 it("should return an array", async function() {29 try {30 await "a,b,c".split(",");31 } catch (err) {32 console.log(err);33 }34 });35});36describe("String#split", function() {37 it("should return an array", async function() {38 try {39 await "a,b,c".split(",");40 } catch (err) {41 console.log(err);42 }43 });44});45describe("String#split", function() {46 it("should return an array", async function() {47 try {48 await "a,b,c".split(",");49 } catch (err) {50 console.log(err);51 }52 });53});54describe("String#split", function() {55 it("should return an array", async function() {56 try {57 await "a,b,c".split(",");58 } catch (err) {59 console.log(err);60 }61 });62});63describe("String#split", function() {64 it("should

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mocha = require('mocha');3var describe = mocha.describe;4var it = mocha.it;5var chai = require('chai');6var expect = chai.expect;7var should = chai.should();8var chaiHttp = require('chai-http');9chai.use(chaiHttp);10var app = require('../app.js');11var mongoose = require('mongoose');12var User = mongoose.model('User');13describe('User', function() {14 it('should be invalid if name is empty', function(done) {15 var u = new User();16 u.validate(function(err) {17 expect(err.errors.name).to.exist;18 done();19 });20 });21});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2 it('should be a function', function() {3 expect(Test).to.be.a('function');4 });5 it('should return a string', function() {6 expect(Test()).to.be.a('string');7 });8});9describe('Test', function() {10 it('should be a function', function() {11 Test.should.be.a('function');12 });13 it('should return a string', function() {14 Test().should.be.a('string');15 });16});17describe('Test', function() {18 it('should be a function', function() {19 expect(Test).to.be.a('function');20 });21 it('should return a string', function() {22 expect(Test()).to.be.a('string');23 });24});25describe('Test', function() {26 it('should be a function', function() {27 Test.should.be.a('function');28 });29 it('should return a string', function() {30 Test().should.be.a('string');31 });32});33describe('Test', function() {34 it('should be a function', function() {35 expect(Test).to.be.a('function');36 });37 it('should return a string', function() {38 expect(Test()).to.be.a('string');39 });40});41describe('Test', function() {42 it('should be a function', function() {43 Test.should.be.a('function');44 });45 it('should return a string', function() {46 Test().should.be.a('string');47 });48});49describe('Test', function() {50 it('should be a function', function() {51 expect(Test).to.be.a('function');52 });53 it('should return a string', function() {54 expect(Test()).to.be.a('string');55 });56});57describe('Test', function() {58 it('should be a function', function()

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var myApp = require('../app/library.js');3describe("Library App", function(){4 describe("Book", function(){5 it("should return all books in the library", function(){6 assert.equal(myApp.books.length, 2);7 })8 })9 describe("Search", function(){10 it("should return a book with a valid id", function(){11 assert.equal(myApp.search(1).title, "The Alchemist");12 })13 it("should return null for invalid id", function(){14 assert.equal(myApp.search(3), null);15 })16 })17 describe("Add", function(){18 it("should add a book to the library", function(){19 assert.equal(myApp.add("The Alchemist", "Paulo Coelho", "978-0062315007"), 3);20 })21 })22 describe("Remove", function(){23 it("should remove a book from the library", function(){24 assert.equal(myApp.remove(1), true);25 })26 })27})28 {

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mymodule = require('./mymodule');3describe('myModule', function(){4 describe('#runnable()', function(){5 it('should return true', function(){6 assert.equal(true,mymodule.runnable());7 })8 })9})10var mymodule = function(){11 this.runnable = function(){12 return true;13 }14}15module.exports = new mymodule();16Mocha also provides a way to write asynchronous tests. You can write asynchronous tests using the done() method. If you are writing an asynchronous test case, you need to pass the done() method to the callback function. The test case will be considered completed only when the done() method is called. If the done() method is not called within a certain time, the test case will be considered as failed. You can also specify the timeout for the test case using the timeout() method. The default

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mocha automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful