Best Python code snippet using localstack_python
qqapi.js
Source:qqapi.js  
...989        }990    }991      , b = function(b, c) {992        c && (b.callback = mqq.callback(a(c), !1, !0)),993        mqq.invoke("qw_data", "getFriendRemark", b)994    }995    ;996    mqq.build("mqq.data.getFriendRemark", {997        iOS: b,998        android: b,999        supportInvoke: !0,1000        support: {1001            iOS: "5.8.0",1002            android: "5.8.0"1003        }1004    })1005}(),1006mqq.build("mqq.data.getPageLoadStamp", {1007    iOS: function(a) {
...InvokeGraph.js
Source:InvokeGraph.js  
1/*2- has a to json method, addInvokes method, calculate, climbTree, descendTree, dedupInvoke, classifyInvoke, classifyCustom3- match every call with parent and children in invoke graph.js (calculates pending edges)4- merge nodes integrate new set of nodes in and dedupes5- backbone collection are fancy arrays with more helper - dedupe unique more methods (ok)6- added helper method for active nodes7*/8define([9  "backbone",10  "underscore",11  "../util/util",12  "text!../util/samples/ibex/invokeSample.txt",13], function (Backbone, _, util, invokeSample) {14  //console.log("invokeSample at beginning of InvokeGraph.js:", invokeSample);15  return Backbone.View.extend({16    rawInvokes: [],17    initialize: function (codeMirrors, sourceCollection, activeNodeCollection, jsBinRouter) {18      this.activeNodeCollection = activeNodeCollection;19      //console.log("activeNodeCollection: ", activeNodeCollection);20      /*_(this.activeNodeCollection.invokes).each(function (ani) {21        console.log("ANI: ", ani);22      });*/23      _(this.returnValueParsers).each(function (fn, i) {24        this.returnValueParsers[i] = _.bind(fn, this);25      }, this);26      _(this.argumentParsers).each(function (fn, i) {27        this.argumentParsers[i] = _.bind(fn, this);28      }, this);29      var instanceId = window.location.pathname.split("/")[1];30      //console.log("going into addInvokes if: ", !instanceId || instanceId.length < 1)31      if (!instanceId || instanceId.length < 1) {32        this.addInvokes(JSON.parse(invokeSample));33      }34    },35    toJSON: function () {36      var serializableInvokes = _(this.invokes).map(function (invoke) {37        var str = invoke.node.source;38        var isos = [];39        if (str) {40          _(str.split("iso_")).each(function (s) {41            var arr = s.split("_iso");42            if (arr.length > 1) {43              isos.push(arr[0])44            }45          });46        }47        return {48          childCalls: _(invoke.childCalls).map(function (i) {49            return i.invocationId50          }),51          childAsyncLinks: _(invoke.childAsyncLinks).map(function (i) {52            return i.invocationId53          }),54          childAsyncSerialLinks: _(invoke.childAsyncSerialLinks).map(function (i) {55            return i.invocationId56          }),57          parentCalls: _(invoke.parentCalls).map(function (i) {58            return i.invocationId59          }),60          parentAsyncLink: invoke.parentAsyncLink ? invoke.parentAsyncLink.invocationId : null,61          parentAsyncSerialLinks: _(invoke.parentAsyncSerialLinks).map(function (i) {62            return i.invocationId63          }),64          invocationId: invoke.invocationId,65          topLevelInvocationId: invoke.invocationId,66          isLib: invoke.invocationId,67          nodeId: invoke.nodeId,68          nodeName: invoke.node.name,69          nodeType: invoke.node.type,70          nodeSource: invoke.node.source ? invoke.node.source.substr(0, 300) : null,71          tick: invoke.tick,72          timestamp: invoke.timestamp,73          parents: invoke.parents,74          arguments: invoke.arguments,75          returnValue: invoke.returnValue,76          functionSerials: isos,77          repeatCallCount: invoke.repeatCallCount,78          aspectMap: invoke.aspectMap79        };80      }, this);81      return JSON.stringify(serializableInvokes, null, 2);82    },83    addInvokes: function (invokes) {84      //console.log("Adding invokes:", invokes.length);85      _(invokes).each(function (invoke) {86        this.rawInvokes.push(invoke);87      }, this);88    },89    calculate: function () {90      var startTime = new Date().getTime();91      console.log("Processing invokes:", this.rawInvokes.length);92      var pendingEdges = [];93      this.invokes = [];94      this.rootInvokes = [];95      this.nativeInvokes = [];96      this.nativeRootInvokes = [];97      this.argSourceToInvokes = [];98      this.invokeIdMap = {};99      this.edges = [];100      this.asyncEdgeMap = {};101      this.asyncEdges = [];102      this.asyncSerialEdgeMap = {};103      this.asyncSerialEdges = [];104      this.maxHitCount = 0;105      this.aspectCollectionMap = {106        click: [],107        wheel: [],108        scroll: [],109        mousemove: [],110        mousedown: [],111        mouseup: [],112        mouseout: [],113        mouseover: [],114        mouseenter: [],115        mouseleave: [],116        keydown: [],117        keypress: [],118        keyup: [],119        ajaxRequest: [],120        ajaxResponse: [],121        domQuery: [],122        jqDom: [],123        setup: []124      };125      126      _(this.activeNodeCollection.models).each(function (nodeModel) {127        nodeModel.set("invokes", []);128        try {129          //console.log("nodeModel:", nodeModel);130          //console.log("nodeModel attributes: ", nodeModel.attributes);131          //console.log("nodeModel name:", nodeModel.attributes.name);132          //console.log("nodeModel src:", nodeModel.attributes.source);133          //console.log("nodeModel path:", nodeModel.attributes.path);134        } catch {135          console.log("couldn't print all")136        }137      });138      var n_nodes_printed = 0;139      // Parse through invokes and populate simple lists of native/lib/top-levels140      _(this.rawInvokes).each(function (rawInvoke) {141        //console.log("rawInvoke before label announcement: ", rawInvoke);142        // Make a copy to leave the original143        var invoke = JSON.parse(JSON.stringify(rawInvoke));144        // invoke doesn't have the node yet145        this.invokes.push(invoke); 146        // adds to this.invokes here (which is what is drawn) 147        invoke.aspectMap = {};148        invoke.getLabel = _.bind(function () {149          return this.getInvokeLabel(invoke);150        }, this);151        this.invokes.push(invoke);152        // pushes invoke again after adding properties153        this.invokeIdMap[invoke.invocationId] = invoke;154        // README LIMITATIONS RELATED NOTE: please see the Limitations section of the readme, there is an issue invokeIdMap not having all the nodes needed to support all orange arrows155        // console.log("added invoke.invocationId to invokeIdMap: ", invoke.invocationId);156        // creating a dictionary from invocationID to invoke157        if (invoke.topLevelInvocationId === invoke.invocationId) {158          this.rootInvokes.push(invoke);159          invoke.rootInvoke = true;160        }161        // mark if invoke is a rootInvoke162        var nodeModel = this.activeNodeCollection.get(invoke.nodeId);163        if (!nodeModel) {164          this.activeNodeCollection.mergeNodes([{165            name: "",166            id: invoke.nodeId,167            source: "",168            invokes: []169          }]);170          // calls mergeNodes on the invoke.nodeId171          nodeModel = this.activeNodeCollection.get(invoke.nodeId);172          console.warn("Creating shell nodemodel for", invoke.nodeId);173        }174        invoke.nodeModel = nodeModel;175        invoke.node = nodeModel.toJSON();176        // adds the node177        if (invoke.rootInvoke){ // node may not be set yet ... 178          //console.log("rootInvoke property true, invoke.nodeModel name: ", invoke.nodeModel.attributes.name, n_nodes_printed, "invoke getLabel(): ", invoke.getLabel(), "invocationId:", invoke.invocationId, "timestamp:", invoke.timestamp); // invoke179        }180        else {181          //console.log("rootInvoke property false, invoke.nodeModel name: ", invoke.nodeModel.attributes.name, n_nodes_printed, "invoke getLabel(): ", invoke.getLabel(),  "invocationId:", invoke.invocationId, "timestamp:", invoke.timestamp); // invoke182        }183        n_nodes_printed++;184        invoke.isLib = util.isKnownLibrary(invoke.nodeId);185        if (!invoke.isLib) {186          //console.log("invoke is not lib");187          this.nativeInvokes.push(invoke);188          var hasParentCaller = !!_(invoke.parents).find(function (parent) {189            return parent.type === "call";190          }); // the !! just checks for truthy191          //console.log("printing invoke.parents to determine why hasParentCaller is truthy:", invoke.parents);192          if (!hasParentCaller) {193            this.nativeRootInvokes.push(invoke);194            invoke.nativeRootInvoke = true;195            //console.log("gets added - 1 invoke.nativeRootInvoke at this stage is: ", invoke.getLabel(), invoke.nativeRootInvoke);196          }197        }198        // keeps track of non-lib "native" function calls (invokes) and "native root" function calls199        // Store parent links to process when the full invokeMap is done200        //console.log("adding edges for each of its parents: ", invoke.parents);201        _(invoke.parents).each(function (parent) {202          // this seems to only cover ORANGE arrow parents203          pendingEdges.push({204            parentAttributes: parent,205            childInvoke: invoke206          });207        }, this);208        // getting node arguments209        //console.log("invoke.arguments: ", invoke.arguments);210        _(invoke.arguments).each(function (arg) {211          if (arg.value && arg.value.type === "function" && arg.value.json) {212            // if we have a function passed as an argument213            var source;214            if (arg.value.json.indexOf("function") === -1) {215              var isoStr = arg.value.json;216              //console.log("isoStr:", isoStr);217              var isoStartIndex = isoStr.indexOf("iso_");218              var isoEndIndex = isoStr.indexOf("_iso");219              // collect the iso serial number220              if (isoStartIndex > -1 && isoEndIndex > -1) {221                var serial = isoStr.substring(isoStartIndex, isoEndIndex + 4);222                var nodeModel = this.activeNodeCollection.serialToNode[serial];223                if (nodeModel) {224                  source = nodeModel.get("source");225                }226              }227            } else {228              source = arg.value.json;229            }230            //console.log("source:", source);231         232            if (!this.argSourceToInvokes[source]) {233              this.argSourceToInvokes[source] = [];234            }235            // Check if we already have this invoke236            var foundInvoke = _(this.argSourceToInvokes[source])237              .find(function (nrInvoke) {238                return nrInvoke.invocationId === invoke.invocationId239              });240            // Store the invoke arg source to be looked up later241            if (!foundInvoke) {242              this.argSourceToInvokes[source].push(invoke);243            }244          }245        }, this);246      }, this);247      // Parse through edges found and create two-way links between parent and child invokes248      // in two different types: direct call (yellow) and tom's async context (orange)249      _(pendingEdges).each(function (edge) {250        if (edge.childInvoke.getLabel().includes("drag"))251          //console.log("pendingEdges childInvoke got till here 1: ", edge.childInvoke.getLabel(), edge.childInvoke);252        if (!edge.parentAttributes || !edge.childInvoke) {253          console.warn("Got some disconnected parent/child invocations.");254          return;255        }256        /*if (edge.childInvoke.getLabel().includes("drag"))257          console.log("pendingEdges childInvoke got till here 2: ", edge.childInvoke.getLabel(), edge.childInvoke);258        */259        var parentInvoke = this.invokeIdMap[edge.parentAttributes.invocationId];260        var parentType = edge.parentAttributes.type;261        var childInvoke = edge.childInvoke;262        if (!parentInvoke || !childInvoke || !parentType) {263          /*if (edge.childInvoke.getLabel().includes("drag")) {264            console.log("edge:", edge);265            if (edge)266              console.log("edge.parentAttributes:", edge.parentAttributes);267            console.log("parentInvoke:", parentInvoke);268            if (edge && edge.parentAttributes)269              console.log("parentType:", edge.parentAttributes.type);270            console.warn("Couldn't find parent/child invocation nodes.");271          }*/272          // README LIMITATIONS RELATED NOTE - added this code to allow purple arrows to be drawn even if some orange are skipped 273          childInvoke.nativeRootInvoke = true;274          this.nativeRootInvokes.push(childInvoke);275          return;276        }277        //if (childInvoke.getLabel().includes("drag"))278        //  console.log("pendingEdges childInvoke got till here 3: ", childInvoke.getLabel(), childInvoke);279        if (parentType === "async") {280          //if (childInvoke.getLabel().includes("drag"))281          //  console.log("pendingEdges childInvoke got till here 4: ", childInvoke.getLabel(), childInvoke);282          if (!parentInvoke.childAsyncLinks) {283            parentInvoke.childAsyncLinks = [];284          }285          if (childInvoke.parentAsyncLink) {286            console.warn("Child invoke has multiple parents async links, should not happen!");287          }288          childInvoke.parentAsyncLink = parentInvoke;289          parentInvoke.childAsyncLinks.push(childInvoke);290          var asyncEdge = {291            parentInvoke: parentInvoke,292            childInvoke: childInvoke293          };294          var edgeId = asyncEdge.parentInvoke.invocationId + asyncEdge.childInvoke.invocationId;295          if (!this.asyncEdgeMap[edgeId]) {296            this.asyncEdgeMap[edgeId] = asyncEdge;297            this.asyncEdges.push(asyncEdge);298          }299        } else if (parentType === "call") {300          //if (childInvoke.getLabel().includes("drag"))301          //  console.log("pendingEdges childInvoke got till here 5: ", childInvoke.getLabel(), childInvoke);302          if (!parentInvoke.childCalls) {303            parentInvoke.childCalls = [];304          }305          if (!childInvoke.parentCalls) {306            childInvoke.parentCalls = [];307          }308          childInvoke.parentCalls.push(parentInvoke);309          parentInvoke.childCalls.push(childInvoke);310          this.edges.push({311            parentInvoke: parentInvoke,312            childInvoke: childInvoke313          });314          // stores the edges and populates child's parent array and parent's child array 315        } else {316          console.log("Found a new parent type", parentType);317        }318        /*console.log("childInvoke.getLabel().includes(drag)", childInvoke.getLabel().includes("drag"));319        if (childInvoke.getLabel().includes("drag")){320          console.log("childInvoke: ", childInvoke.getLabel(), childInvoke);321          console.log("childInvoke.isLib: ", childInvoke.isLib);322          console.log("parentInvoke.isLib: ", parentInvoke.isLib);323        }*/324        if (!childInvoke.isLib && parentInvoke.isLib) {325          if (!childInvoke.nativeRootInvoke) {326            childInvoke.nativeRootInvoke = true;327            //console.log("gets added - 2 childInvoke.nativeRootInvoke at this stage is: ", childInvoke.getLabel(), childInvoke.invocationId, childInvoke.timestamp, childInvoke.nativeRootInvoke);328            this.nativeRootInvokes.push(childInvoke);329          }330        }331      }, this);332      // Parse through invoke arguments to determine final missing async serial links333      _(this.nativeRootInvokes).each(function (childInvoke) {334        if (childInvoke.node && childInvoke.node.name) {335          //console.log("name: ", childInvoke.node.name);336        }337        if (!childInvoke.node.source) {338          return;339        }340        //console.log("childInvoke: ", childInvoke.getLabel());341        //console.log("childInvoke.node.source", childInvoke.node.source);342        var parentInvokes = this.argSourceToInvokes[childInvoke.node.source]; 343        344        //console.log("childInvoke is:", childInvoke.getLabel(), childInvoke.timestamp);345        //console.log("parentInvokes are: ", parentInvokes);346        if (parentInvokes) {347          // HEURISTIC: only show purple line for closest async parent348          // THIS IS KEY TO PURPLE LINES349          // go from timewise latest parents to timewise earliest350          parentInvokes = parentInvokes.sort((a,b) => (a.tick > b.tick) ? 1 : ((b.tick > a.tick) ? -1 : 0));351          parentInvokes = parentInvokes.reverse(); 352          for (var pi = 0; pi < parentInvokes.length; pi++){353            parentInvoke = parentInvokes[pi];354            //console.log("nativeRootInvoke childInvoke ts is: ", childInvoke.timestamp, childInvoke);355            //console.log("parentInvoke ts is: ", parentInvoke.timestamp, parentInvoke);356            if (!parentInvoke.childAsyncSerialLinks) {357              parentInvoke.childAsyncSerialLinks = [];358            }359            if (!childInvoke.parentAsyncSerialLinks) {360              childInvoke.parentAsyncSerialLinks = [];361            }362            childInvoke.parentAsyncSerialLinks.push(parentInvoke);363            parentInvoke.childAsyncSerialLinks.push(childInvoke);364            var asyncSerialEdge = {365              parentInvoke: parentInvoke,366              childInvoke: childInvoke367            };368            var edgeId = asyncSerialEdge.parentInvoke.invocationId + asyncSerialEdge.childInvoke.invocationId;369            if (!this.asyncSerialEdgeMap[edgeId]) {370              this.asyncSerialEdgeMap[edgeId] = asyncSerialEdge;371              if (parentInvoke.tick < childInvoke.tick){ // should we use fondue's tick instead?372                this.asyncSerialEdges.push(asyncSerialEdge); 373                //console.log("pushed an async serial edge to: ", asyncSerialEdge.childInvoke.getLabel(), asyncSerialEdge);374                return false; // break out of loop375              }376            }377          }   378        }379      }, this);380      // Add setup attribute to all first tree nodes381      if (this.nativeInvokes[0]) {382        this.nativeInvokes[0].aspectMap["page load"] = true;383        var setupCollection = this.aspectCollectionMap.setup;384        this.descendTree(this.nativeInvokes[0], function (node) {385          node.aspectMap["setup"] = true;386          setupCollection.push(node);387        });388      }389      // Place invokes into queryable buckets390      _(this.invokes).map(this.classifyInvoke, this);391      var stopTime = new Date().getTime();392      console.log("Done processing invokeGraph", parseInt((stopTime - startTime) / 1000), "seconds");393    },394    climbTree: function (node, decorator, stopCondition) {395      decorator(node);396      if (stopCondition && stopCondition(node)) {397        return;398      }399      // Otherwise keep climbing400      _(node.parentCalls).find(function (parentNode) {401        return this.climbTree(parentNode, decorator, stopCondition)402      }, this);403    },404    descendTree: function (node, decorator, stopCondition) {405      decorator(node);406      if (stopCondition && stopCondition(node)) {407        return;408      }409      _(node.childCalls).each(function (node) {410        this.descendTree(node, decorator, stopCondition)411      }, this);412    },413    decorateAspect: function (node, aspect, nodeAspectArr) {414      var decorator = function (invokeNode) {415        invokeNode.aspectMap[aspect] = true;416        if (nodeAspectArr) {417          nodeAspectArr.push(invokeNode);418        }419      };420      decorator = _.bind(decorator, this);421      decorator(node);422      this.climbTree(node, decorator, null);423      // if (node.isLib) {424      //   var stopCondition = function (node) {425      //     return !node.isLib;426      //   };427      this.descendTree(node, decorator, null)428      // }429    },430    parseEventFromArg: function (arg) {431      if (arg && arg.value && arg.value.ownProperties) {432        // jQuery 2, zepto event bindings433        if (arg.value.ownProperties.eventName) {434          if (arg.value.ownProperties.eventName.value.indexOf("Event") > -1) {435            if (arg.value.ownProperties.type) {436              return arg.value.ownProperties.type.value;437            }438          }439        } else if (arg.value.ownProperties.originalEvent) {440          // jQuery 1 event bindings441          if (arg.value.ownProperties.originalEvent.preview) {442            if (arg.value.ownProperties.originalEvent.preview.indexOf("Event") > -1) {443              if (arg.value.ownProperties.type) {444                return arg.value.ownProperties.type.value;445              }446            }447          }448        }449      }450      return null;451    },452    mouseEvents: [453      "click",454      "wheel",455      "scroll",456      "mousemove",457      "mousedown",458      "mouseup",459      "mouseout",460      "mouseover",461      "mouseenter",462      "mouseleave"463    ],464    keyEvents: [465      "keydown",466      "keypress",467      "keyup"468    ],469    ajaxEvents: [470      "ajaxStart",471      "ajaxRequest",472      "ajaxResponse"473    ],474    domQueries: [475      "domQuery",476      "jqDom"477    ],478    argumentParsers: [479      function (arg) {480        return this.parseEventFromArg(arg);481      },482      function (arg) {483        try {484          if ((arg.value.ownProperties.type.value === "load" ||485            arg.value.ownProperties.type.value === "readystatechange" ||486            arg.value.ownProperties.type.value === "xmlhttprequest") &&487            arg.value.ownProperties.status.value !== 0 &&488            arg.value.ownProperties.status.type === "number") {489            return "ajaxResponse";490          }491        } catch (ignored) {492        }493        return null;494      }495    ],496    returnValueParsers: [497      function (returnValue) {498        try {499          if (returnValue.ownProperties.length &&500            returnValue.ownProperties.selector.value) {501            return "jqDom";502          }503        } catch (ignored) {504          return null;505        }506      },507      function (returnValue) {508        try {509          if (returnValue.ownProperties.elementType &&510            returnValue.ownProperties.elementType.value.indexOf("HTML") > -1) {511            return "domQuery";512          }513        } catch (ignored) {514          return null;515        }516      },517      function (returnValue) {518        try {519          if (returnValue.ownProperties.type.value === "xmlhttprequest" ||520            returnValue.ownProperties.status.value === 0) {521            return "ajaxRequest";522          }523        } catch (ignored) {524          return null;525        }526      }527    ],528    deDupInvoke: function (invoke) {529      if (invoke.nodeModel) {530        var nodeInvokes = invoke.nodeModel.get('invokes');531        if (nodeInvokes.length > 0) {532          var hasPriorInvoke = false;533          var nodeMatch = function (invokeA, invokeB) {534            var a = _(invokeA.parentCalls || []).pluck("nodeId").join("");535            a += _(invokeA.childCalls || []).pluck("nodeId").join("");536            var b = _(invokeB.parentCalls || []).pluck("nodeId").join("");537            b += _(invokeB.childCalls || []).pluck("nodeId").join("");538            return a === b;539          };540          _(nodeInvokes).each(function (subInvoke) {541            if (nodeMatch(invoke, subInvoke)) {542              hasPriorInvoke = true;543              subInvoke.isSequentialRepeat = true;544            }545          }, this);546          if (hasPriorInvoke) {547            // Set latest invoke as the non-repeat548            invoke.isSequentialRepeat = false;549          }550        }551        nodeInvokes.push(invoke);552      }553    },554    classifyInvoke: function (invoke) {555      this.deDupInvoke(invoke);556      if (!this.maxHitCount || invoke.node.invokes.length > this.maxHitCount) {557        this.maxHitCount = invoke.node.invokes.length;558      }559      if (invoke.node && invoke.node.name &&560        (invoke.node.name === "('$' callback)" || invoke.node.name.indexOf(".js toplevel") > -1)) {561        invoke.aspectMap["setup"] = true;562        this.aspectCollectionMap.setup.push(invoke);563      }564      // Check return values565      _(this.returnValueParsers).each(function (parser) {566        var aspect = parser(invoke.returnValue);567        if (aspect) {568          this.decorateAspect(invoke, aspect, this.aspectCollectionMap[aspect]);569        }570      }, this);571      // Comb through arguments572      _(invoke.arguments).each(function (arg) {573        _(this.argumentParsers).each(function (parser) {574          var aspect = parser(arg);575          if (aspect) {576            this.decorateAspect(invoke, aspect, this.aspectCollectionMap[aspect]);577          }578        }, this);579      }, this);580    },581    classifyCustom: function (aspect, argTestFn, returnValTestFn) {582      if (!aspect || !(argTestFn || returnValTestFn)) {583        console.warn("Tried classify custom without required params.");584        return;585      }586      var testFn;587      if (argTestFn) {588        testFn = function (invoke) {589          return !!_(invoke.arguments).find(function (arg) {590            return argTestFn(util.unMarshshalVal(arg.value))591          })592        }593      } else if (returnValTestFn) {594        testFn = function (invoke) {595          return invoke.returnValue && !!returnValTestFn(util.unMarshshalVal(invoke.returnValue));596        }597      }598      _(this.invokes).each(function (invoke) {599        var hasAspect;600        try {601          hasAspect = testFn(invoke)602        } catch (ignored) {603        }604        if (hasAspect) {605          this.decorateAspect(invoke, aspect, null);606        }607      }, this);608    },609    getInvokeLabel: function (invoke) {610      if (invoke.node.customLabel) {611        return invoke.node.customLabel;612      }613      var aspects = invoke.aspectMap ? _(invoke.aspectMap).keys().join(", ") : "";614      var name = invoke.node.name;615      // var root = invoke.rootInvoke ? "rootInvoke" : "";616      // var nativeRoot = invoke.nativeRootInvoke ? "nativeRootInvoke" : "";617      var hits = invoke.node.invokes.length;618      if (aspects) {619        aspects = "[" + aspects + "]"620      }621      return [aspects, name, "Ã", hits].join(" ");622    },623    sort: function () {624      this.invokes.sort(function (a, b) {625        if (a.timestamp > b.timestamp) {626          return 1;627        } else if (a.timestamp < b.timestamp) {628          return -1;629        } else {630          // Secondary sort on tick631          if (a.tick > b.tick) {632            return 1;633          } else if (a.tick < b.tick) {634            return -1;635          } else {636            return 0;637          }638        }639      });640    }641  });...CallGraphView.js
Source:CallGraphView.js  
1/*2-  compiles all the graphs collections and draws the graph3- all bottom buttons laid out here, sets up custom colors, functions for all the buttons, draws async relations (Josh, Tom fondue); coloring of invoke nodes (blue, toplevel, ajax, click, etc); handlesNodeClick, handlesEdgeClick, heatmap, updates label, draws the actual graph; defines other buttons as well like downloading invokes etc4*/5define([6  "jquery",7  "backbone",8  "underscore",9  "handlebars",10], function ($, Backbone, _, Handlebars) {11  return Backbone.View.extend({12    events: {13      "click #draw": "draw", // comes from this.invokeGraph14      "click #markNonLib": "markNonLib",15      "click #markTopLevelNonLib": "markTopLevelNonLib",16      "click #drawTomAsync": "drawTomAsync",17      "click #drawJoshAsync": "drawJoshAsync",18      "click #pruneGraph": "pruneGraph",19      "click #resetGraph": "resetGraph",20      "click #markAllBlue": "markAllBlue",21      "click #markAjaxRequest": "markAjaxRequest",22      "click #markAjaxResponse": "markAjaxResponse",23      "click #markClick": "markClick",24      "click #hideRepeats": "hideRepeats",25      "click #hideLibs": "hideLibs",26      "click #hideUnknownAspectNodes": "hideUnknownAspectNodes",27      "click #showLibCode": "showLibCode",28      "click #showRepeats": "showRepeats",29      "click #showUnknown": "showUnknown",30      "click #drawHeatMap": "drawHeatMap",31      "click #downloadInvokes": "downloadInvokes",32      "click #downloadNodes": "downloadNodes",33    },34    customColors: {},35    colors: {36      nativeNode: "#bce9fd",37      libNode: "#bdbdbd",38      edge: "#e6da74",39      nativeRootInvoke: "#48ff60",40      asyncEdge: "#fd9620",41      asyncSerialEdge: "#bc95ff",42      ajaxStart: "#fff",43      ajaxRequest: "#fff",44      ajaxResponse: "#dd7382",45      domQuery: "#bc95ff",46      jqDom: "#bc95ff",47      mouseEvent: "#fd9620",48      click: "#fd9620",49      wheel: "#fd9620",50      mousemove: "#fd9620",51      mousedown: "#fd9620",52      mouseup: "#fd9620",53      mouseout: "#fd9620",54      mouseleave: "#fd9620",55      mouseenter: "#fd9620",56      mouseover: "#fd9620",57      selected: "#fff07b",58      edgeSelected: "#f7f7f7",59    },60    aspectFilters: [],61    negatedAspectFilters: [],62    draw: function () {63      this.invokeGraph.calculate();64      this.resetGraph();65    },66    initialize: function (invokeGraph, activeNodeCollection) {67      this.invokeGraph = invokeGraph;68      this.activeNodeCollection = activeNodeCollection;69      this.setElement($("#graphView"));  // el should be in the dom at instantiation time70      this.$("#invokeGraph").height(parseInt(this.$el.height()) - parseInt(this.$("#graphControl").height()));71      this.filterByAspect = _.bind(this.filterByAspect, this);72      this.handleNodeClick = _.bind(this.handleNodeClick, this);73      this.handleEdgeClick = _.bind(this.handleEdgeClick, this);74      this.addCustomColor = _.bind(this.addCustomColor, this);75    },76    addCustomColor: function (aspect, color) {77      this.customColors[aspect] = color;78    },79    hideLibs: function () {80      this.showLibs = false;81      this.drawGraph();82    },83    hideRepeats: function () {84      this.showSequentialRepeats = false;85      this.drawGraph();86    },87    hideUnknownAspectNodes: function () {88      this.showUnknownAspects = false;89      this.drawGraph();90    },91    showLibCode: function () {92      this.showLibs = true;93      this.drawGraph();94    },95    showRepeats: function () {96      this.showSequentialRepeats = true;97      this.drawGraph();98    },99    showUnknown: function () {100      this.showUnknownAspects = true;101      this.drawGraph();102    },103    drawHeatMap: function () {104      _(this.visibleInvokes).each(function (invoke) {105        var heatColor = this.calcHeatColor(invoke.node.invokes.length, this.maxVisibleHitCount);106        this.cy.elements('node[id = "' + invoke.invocationId + '"]')107          .style({"background-color": heatColor});108      }, this);109    },110    resetGraph: function () {111      this.lastSelectedNodes = [];112      this.lastSelectedEdge = null;113      this.visibleInvokes = [];114      this.maxVisibleHitCount = 0;115      this.hideInvokeIdMap = {};116      this.showLibs = false;117      this.showSequentialRepeats = false;118      this.showUnknownAspects = false;119      this.drawGraph();120    },121    drawJoshAsync: function () {122      //console.log("Drawing async serial connections."); // ok this triggers the creation of purple arrows123      _(this.invokeGraph.asyncSerialEdges).each(function (edge, i, arr) {124        //console.log("drawJoshAsync - asyncSerialEdge: ", edge, "i: ", i, "arr: ", arr);125        //console.log("drawJoshAsync - parent: ", edge.parentInvoke.node.name, "child:", edge.childInvoke.node.name);126        if (this.hideInvokeIdMap[edge.parentInvoke.invocationId] ||127          this.hideInvokeIdMap[edge.childInvoke.invocationId]) {128          return;129        }130        var edgeElement = this.cy.elements('edge[source = "' + edge.parentInvoke.invocationId + '"][target="' + edge.childInvoke.invocationId + '"]');131        if (!edgeElement.length) {132          this.cy.add({133            group: 'edges', data: {134              source: edge.parentInvoke.invocationId,135              target: edge.childInvoke.invocationId,136              color: this.colors.asyncSerialEdge137            }138          });139        }140      }, this);141    },142    drawTomAsync: function () { // ok this triggers the creation of oranges arrows143      _(this.invokeGraph.asyncEdges).each(function (edge) {144        this.cy.remove('edge[source = "' + edge.parentInvoke.invocationId + '"][target="' + edge.childInvoke.invocationId + '"]');145        this.cy.add({146          group: 'edges', data: {147            source: edge.parentInvoke.invocationId,148            target: edge.childInvoke.invocationId,149            color: this.colors.asyncEdge150          }151        });152      }, this);153    },154    markAspectColor: function (aspectArr, color) {155      if (!aspectArr || !color) {156        console.warn("Tried to color invoke node without params.");157        return;158      }159      var allNodes = (aspectArr === "*");160      _(this.visibleInvokes).each(function (invoke) {161        var markAspect;162        if (allNodes) {163          markAspect = true;164        } else {165          markAspect = _(aspectArr).find(function (aspect) {166            return invoke.aspectMap[aspect];167          });168        }169        if (markAspect) {170          this.cy.elements('node[id = "' + invoke.invocationId + '"]')171            .style({"background-color": color});172        }173      }, this);174    },175    markAllBlue: function () {176      this.markAspectColor("*", this.colors.nativeNode);177    },178    markTopLevelNonLib: function () {179      _(this.invokeGraph.nativeRootInvokes).each(function (invoke) {180        this.cy.elements('node[id = "' + invoke.invocationId + '"]')181          .style({182            "background-color": this.colors.nativeRootInvoke183          });184      }, this);185    },186    markAjaxRequest: function () {187      this.markAspectColor(["ajaxRequest"], this.colors.ajaxRequest);188    },189    markAjaxResponse: function () {190      this.markAspectColor(["ajaxResponse"], this.colors.ajaxResponse);191    },192    markClick: function () {193      this.markAspectColor(this.invokeGraph.mouseEvents, this.colors.mouseEvent);194    },195    filterByAspect: function (aspectArr, negateAspectArr) {196      this.aspectFilters = aspectArr;197      this.negatedAspectFilters = negateAspectArr;198      this.drawGraph();199    },200    resetLastNodes: function () {201      if (!this.lastSelectedNodes.length) {202        return;203      }204      _(this.lastSelectedNodes).each(function (node) {205        this.cy.elements('node[id = "' + node.id + '"]')206          .style({207            "background-color": node.color,208            "border-color": "none",209            "border-width": "0"210          });211      }, this);212      this.lastSelectedNodes = [];213      if (this.lastSelectedEdge) {214        var edgeElement = this.cy.elements('edge[source = "' + this.lastSelectedEdge.sourceId + '"][target = "' + this.lastSelectedEdge.targetId + '"]');215        if (!edgeElement.length) {216          edgeElement = this.cy.elements('edge[target = "' + this.lastSelectedEdge.sourceId + '"][source = "' + this.lastSelectedEdge.targetId + '"]');217        }218        edgeElement.style({219          "line-color": this.lastSelectedEdge.color220        });221        this.lastSelectedEdge = null;222      }223    },224    handleNodeClick: function (nodeId, silent) {225      this.resetLastNodes();226      //console.log("Clicked invoke id:", nodeId);227      this.lastSelectedNodes = [{228        id: nodeId,229        color: this.cy.elements('node[id = "' + nodeId + '"]').style("background-color")230      }];231      this.cy.elements('node[id = "' + nodeId + '"]')232        .style({233          "background-color": this.colors.selected,234          "border-color": "white",235          "border-width": "3px"236        });237      if (!silent) {238        this.trigger("nodeClick", nodeId);239      }240    },241    handleEdgeClick: function (sourceId, targetId, silent) {242      this.resetLastNodes();243      _([sourceId, targetId]).each(function (nodeId) {244        this.lastSelectedNodes.push({245          id: nodeId,246          color: this.cy.elements('node[id = "' + nodeId + '"]').style("background-color")247        });248        this.cy.elements('node[id = "' + nodeId + '"]')249          .style({250            "background-color": this.colors.selected,251            "border-color": "white",252            "border-width": "3px"253          });254      }, this);255      var edgeElement = this.cy.elements('edge[source = "' + sourceId + '"][target = "' + targetId + '"]');256      if (!edgeElement.length) {257        edgeElement = this.cy.elements('edge[target = "' + sourceId + '"][source = "' + targetId + '"]');258      }259      this.lastSelectedEdge = {260        sourceId: sourceId,261        targetId: targetId,262        color: edgeElement.style("line-color")263      };264      edgeElement265        .style({266          "line-color": this.colors.edgeSelected,267        });268      if (!silent) {269        this.trigger("edgeClick", [sourceId, targetId]);270      }271    },272    getNodeColor: function (node) {273      var customColors = _(this.customColors).keys();274      if (customColors.length) {275        var colorKey = _(customColors).find(function (aspect) {276          return node.aspectMap[aspect];277        });278        if (colorKey) {279          return this.customColors[colorKey];280        }281      }282      if (node.isLib) {283        return this.colors.libNode;284      }285      if (node.nativeRootInvoke) {286        return this.colors.nativeRootInvoke;287      }288      var aspectArr = _(node.aspectMap).keys();289      var last = _(aspectArr).last();290      if (this.colors[last]) {291        return this.colors[last];292      }293      return this.colors.nativeNode;294    },295    calcHeatColor: function (val, max) {296      var heatNum = val / max;297      var r = parseInt(heatNum * 255);298      var b = 255 - r;299      return "#" + ((1 << 24) + (r << 16) + (0 << 8) + b).toString(16).slice(1);300    },301    updateLabel: function (invokeId) {302      this.cy.elements('node[id = "' + invokeId + '"]')303        .data("label", this.invokeGraph.invokeIdMap[invokeId].getLabel());304    },305    childrenHaveAsyncChild: function childrenHaveAsyncChild(invoke) {306      if (invoke.childAsyncSerialLinks && invoke.childAsyncSerialLinks.length > 0)307        return true;308      if (invoke.childCalls) {309        for (var i = 0; i < invoke.childCalls.length; i++) {310          var child_invoke = invoke.childCalls[i];311          if (childrenHaveAsyncChild(child_invoke))312            return true;313        }314      }315      return false;316    },317    drawGraph: function () {318      //console.log("Emptying old graph.")319      this.$("#invokeGraph").empty();320      this.hideInvokeIdMap = {};321      this.maxVisibleHitCount = 0;322      var n_nodes_shown = 0;323      var nodes = _(this.invokeGraph.invokes).reduce(function (displayNodes, invoke) {324        //console.log("CGV node:", invoke.node);325        //console.log("CGV node name:", invoke.node.name);326        //console.log("CGV node source:", invoke.node.source);327        if (!this.showLibs && invoke.isLib) {328          //console.log("it is considered a lib");329          this.hideInvokeIdMap[invoke.invocationId] = true;330          return displayNodes;331        }332        if (!this.showUnknownAspects && _(invoke.aspectMap).keys().length < 1) {333          //console.log("it is considered an unknown aspect");334          //console.log("invoke:", invoke);335          //console.log("invoke.aspectMap: ", invoke.aspectMap);336          //console.log("_(invoke.aspectMap): ", _(invoke.aspectMap));337          //console.log("_(invoke.aspectMap).keys()", _(invoke.aspectMap).keys());338          this.hideInvokeIdMap[invoke.invocationId] = true;339          return displayNodes;340        }341        if (!this.showSequentialRepeats && invoke.isSequentialRepeat) {342          //console.log("it is considered a sequential repeat");343          this.hideInvokeIdMap[invoke.invocationId] = true;344          return displayNodes;345        }346        if (this.aspectFilters.length) {347          //console.log("need to check some aspectFilters");348          var found = _(this.aspectFilters).find(function (aspect) {349            return invoke.aspectMap[aspect]350          });351          if (!found) {352            this.hideInvokeIdMap[invoke.invocationId] = true;353            return displayNodes;354          }355        }356        if (this.negatedAspectFilters.length) {357          //console.log("need to check negatedAspectFilters");358          var negateFound = _(this.negatedAspectFilters).find(function (aspect) {359            return invoke.aspectMap[aspect]360          });361          if (negateFound) {362            this.hideInvokeIdMap[invoke.invocationId] = true;363            return displayNodes;364          }365        }366        //console.log("considering invoke: ", invoke.getLabel());367        //console.log("invoke.nativeRootInvoke: ", invoke.nativeRootInvoke);368        //console.log("invoke.childAsyncSerialLinks: ", invoke.childAsyncSerialLinks);369        //console.log("invoke: ", invoke);370        if (!invoke.nativeRootInvoke){371          // only show nodes that are top level calls372          if (!invoke.childAsyncSerialLinks || invoke.childAsyncSerialLinks.length < 1) { 373            // or they have async children374            //console.log("childrenHaveAsyncChild(invoke):", this.childrenHaveAsyncChild(invoke));375            if (!this.childrenHaveAsyncChild(invoke)) {376              // or they have descendents that have async children377              378              // COMMMENT FOLLOWING LINES TO TEMPORARILY DEBUG:379              this.hideInvokeIdMap[invoke.invocationId] = true;380              return displayNodes;381            }382          }383        }384        /*if (invoke.topLevelInvocationId != invoke.invocationId) {385          return displayNodes;386        }*/ // true way of getting top level nodes only, but excludes those with async children387        if (this.hideInvokeIdMap[invoke.invocationId]) {388          //console.log("it is explicitly in the hideInvokeIdMap");389          return displayNodes;390        }391        var label = invoke.getLabel();392        393        if (invoke.nativeRootInvoke) { // considering only top level calls394          var events_to_parse_out = ["load", "resize", "scroll", "unload", "change", "copy", "focus", "keydown, keypress, keyup", "paste", "reset", "select", "submit", "copy, cut, paste", "keydown", "keypress", "keyup", "click", "contextmenu", "dblclick", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "right click", "scrolling"]395          for (i = 0; i < events_to_parse_out.length; i++) {396            ev = events_to_parse_out[i];397            if (label.includes("[" + ev)) {398              // deal with xN399              var fn = label.search(/]/i)400              var xn = label.search(/\sÃ\s[0-9]/i)401              var fn_text = label.substr(fn+1, xn-(fn+1)).trim()402              var xn_text = label.substr(xn)403              label = "[" + ev + " callback] " + fn_text + xn_text; // *404              break;405            }406          }407        }408        console.log("label:", label, "invoke.childAsyncSerialLinks: ", invoke.childAsyncSerialLinks);409        if (invoke.childAsyncSerialLinks){410          var label_has_been_set = false;411          for (var aci = 0; aci < invoke.childAsyncSerialLinks.length; aci++){412            async_child = invoke.childAsyncSerialLinks[aci];413            console.log("async_child:", async_child);414            var events_to_parse_out = ["load", "resize", "scroll", "unload", "change", "copy", "focus", "keydown, keypress, keyup", "paste", "reset", "select", "submit", "copy, cut, paste", "keydown", "keypress", "keyup", "click", "contextmenu", "dblclick", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "right click", "scrolling"]415            for (i = 0; i < events_to_parse_out.length; i++) {416              ev = events_to_parse_out[i];417              if (async_child.getLabel().includes("[" + ev)) {418                // deal with xN419                var fn = label.search(/]/i)420                var xn = label.search(/\sÃ\s[0-9]/i)421                var fn_text = label.substr(fn+1, xn-(fn+1)).trim()422                var xn_text = label.substr(xn)423                console.log("invoke.node.source:", invoke.node.source);424                if (invoke.node.source.includes(".off(") || invoke.node.source.includes(".unbind(")) {425                  label = "[" + ev + " unbinding] " + fn_text + xn_text; // *426                  console.log("label:", label);427                  label_has_been_set = true;428                }429                else {430                  label = "[" + ev + " binding] " + fn_text + xn_text; // *431                  console.log("label:", label);432                  label_has_been_set = true; 433                }434                //if (label.includes("mousemove")) 435                //  console.log("mousemove invoke: ", invoke);436                break;437              }438            }439            if (label_has_been_set) break;440          }441        }442        443        //console.log("node to be drawn:", invoke);444        var node = {445          data: {446            id: invoke.invocationId,447            label: label,448            color: this.getNodeColor(invoke) // "#d13r23"449          }450        };451        //console.log(n_nodes_shown, "node getting shown: ", invoke.getLabel()); 452        n_nodes_shown++;453        //console.log("node:", label);454        this.visibleInvokes.push(invoke);455        if (invoke.node.invokes.length > this.maxVisibleHitCount) {456          this.maxVisibleHitCount = invoke.node.invokes.length;457        }458        displayNodes.push(node);459        return displayNodes;460      }, [], this);461      //console.log("Filtered to node count", nodes.length, "of", this.invokeGraph.invokes.length);462      var edges = _(this.invokeGraph.edges).reduce(function (displayEdges, edge) {463        if (this.hideInvokeIdMap[edge.parentInvoke.invocationId] ||464          this.hideInvokeIdMap[edge.childInvoke.invocationId]) {465          return displayEdges;466        }467        //console.log("drawGraph - edge: ", edge)468        //console.log("drawGraph - parent: ", edge.parentInvoke.node.name, "child:", edge.childInvoke.node.name);469        displayEdges.push({470          data: {471            source: edge.parentInvoke.invocationId,472            target: edge.childInvoke.invocationId,473            color: this.colors.edge474          }475        });476        return displayEdges;477      }, [], this);478      //console.log("Filtered to edge count", edges.length, "of", this.invokeGraph.edges.length);479      //console.log("Drawing graph...");480      this.cy = cytoscape({481        container: this.$("#invokeGraph")[0],482        boxSelectionEnabled: false,483        autounselectify: true,484        layout: {485          name: 'dagre',486          avoidOverlap: true,487          pan: 'fix',488          fit: true,489          padding: 20,490          minLen: function (edge) {491            return 2;492          }493        },494        style: [495          {496            selector: 'node',497            style: {498              'min-zoomed-font-size': 6,499              // 'font-family': 'system, "helvetica neue"',500              // 'font-size': 14,501              // 'font-weight': 400,502              'shape': 'roundrectangle',503              // 'overlay-color': "white",504              // 'overlay-padding': 1,505              'width': 'label',506              'height': 'label',507              'padding': 8,508              'content': 'data(label)',509              // 'text-opacity': 1,510              'text-valign': 'center',511              // 'text-halign': 'center',512              // 'color': "black",513              'background-color': 'data(color)'514            }515          },516          {517            selector: 'edge',518            style: {519              'width': 2,520              'target-arrow-shape': 'triangle',521              'line-color': 'data(color)',522              'target-arrow-color': 'data(color)',523              'curve-style': 'bezier'524            }525          }526        ],527        elements: {528          nodes: nodes,529          edges: edges530        },531      });532      //console.log("cy:", this.cy);533      //console.log("cy.nodes:", this.cy.nodes());534      // get all the nodes and stagger them535      // Returns a random number between min (inclusive) and max (exclusive)536      function getRandomArbitrary(min, max) {537        return Math.random() * (max - min) + min;538      } // thanks to http://man.hubwiz.com/docset/JavaScript.docset/Contents/Resources/Documents/developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random.html539      this.cy.nodes().forEach(function(ele){540        //console.log("in cy nodes each: ", ele);541        //console.log("in cy nodes each node pos: ", ele.position());542        ele_pos = ele.position();543        ele_pos.y += getRandomArbitrary(-50, 50);544        ele.position(ele_pos);545      })546      var callGraphView = this;547      this.cy.on('click', 'node', function () {548        callGraphView.handleNodeClick(this.id());549      });550      this.cy.on('click', 'edge', function () {551        callGraphView.handleEdgeClick(this.data("source"), this.data("target"));552      });553      //console.log("Graph initial draw done.");554      // this.drawJoshAsync();555      //console.log("DrawGraph completed.");556    },557    downloadInvokes: function () {558      this.downloadStr(JSON.stringify(this.invokeGraph.rawInvokes, null, 2), "invokeSample.txt");559    },560    downloadNodes: function () {561      this.downloadStr(JSON.stringify(this.activeNodeCollection.rawNodes, null, 2), "nodeSample.txt");562    },563    downloadStr: function (str, fileName) {564      var textFileAsBlob = new Blob([str], {type: 'text/plain'});565      var downloadLink = document.createElement("a");566      downloadLink.download = fileName;567      downloadLink.innerHTML = "Download File";568      downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);569      downloadLink.click();570    }571  });...event-tests.js
Source:event-tests.js  
...226        t.equal(event.payload.toString(), "Event 0," + evtstring, "Successfully received expected chaincode event payload");227        eh.unregisterChaincodeEvent(regid);228    });229    // Trigger the invoke transaction230    var invokeTx = test_user_Member1.invoke(invokeRequest);231    // set timout on event sent by chaincode invoke232    timeoutId = setTimeout(function() {233                                 if(timedout) {234                                     eh.unregisterChaincodeEvent(regid);235                                     t.fail("Failed to receive chaincode event");236                                     process.exit(1);237                                 }238                             },239                             duration);240    // Print the invoke results241    invokeTx.on('complete', function (results) {242        // Invoke transaction submitted successfully243        t.pass(util.format("Successfully completed chaincode invoke transaction: request=%j, response=%j", invokeRequest, results));244    });245    invokeTx.on('error', function (err) {246        // Invoke transaction submission failed247        t.fail(util.format("Failed to submit chaincode invoke transaction: request=%j, error=%j", invokeRequest, err));248        // Exit the test script after a failure249        process.exit(1);250    });251});252//253// Issue a chaincode invoke to generate event and listen for the event254// on 2 registrations255//256test('Invoke chaincode, have it generate an event, and receive event on 2 registrations', function (t) {257    t.plan(3);258    var evtstring = "event-test";259    // Construct the invoke request260    var invokeRequest = {261        // Name (hash) required for invoke262        chaincodeID: testChaincodeID,263        // Function to trigger264        fcn: "invoke",265        // Parameters for the invoke function266        args: [evtstring]267    };268    var eh = chain.getEventHub();269    var duration = chain.getInvokeWaitTime() * 1000;270    var timedout = true;271    var timeoutId = null;272    var eventcount = 0;273    // register for chaincode event274    var regid1 = eh.registerChaincodeEvent(testChaincodeID, "^evtsender$", function(event) {275        eventcount++;276        if (eventcount > 1) {277            if (timeoutId) {278                clearTimeout(timeoutId);279            }280        }281        t.equal(event.payload.toString(), "Event 1," + evtstring, "Successfully received expected chaincode event payload");282        eh.unregisterChaincodeEvent(regid1);283    });284    // register for chaincode event285    var regid2 = eh.registerChaincodeEvent(testChaincodeID, "^evtsender$", function(event) {286        eventcount++;287        if (eventcount > 1) {288            if (timeoutId) {289                clearTimeout(timeoutId);290            }291        }292        t.equal(event.payload.toString(), "Event 1," + evtstring, "Successfully received expected chaincode event payload");293        eh.unregisterChaincodeEvent(regid2);294    });295    // Trigger the invoke transaction296    var invokeTx = test_user_Member1.invoke(invokeRequest);297    // set timout on event sent by chaincode invoke298    timeoutId = setTimeout(function() {299                                 if(eventcount > 1) {300                                     eh.unregisterChaincodeEvent(regid1);301                                     eh.unregisterChaincodeEvent(regid2);302                                     t.fail("Failed to receive chaincode event");303                                     process.exit(1);304                                 }305                             },306                             duration);307    // Print the invoke results308    invokeTx.on('complete', function (results) {309        // Invoke transaction submitted successfully310        t.pass(util.format("Successfully completed chaincode invoke transaction: request=%j, response=%j", invokeRequest, results));311    });312    invokeTx.on('error', function (err) {313        // Invoke transaction submission failed314        t.fail(util.format("Failed to submit chaincode invoke transaction: request=%j, error=%j", invokeRequest, err));315        // Exit the test script after a failure316        process.exit(1);317    });318});319//320// Issue a chaincode invoke to generate event and listen for the event321// by registering with chaincode id and wildcarded event name322//323test('Generate chaincode event and receive it with wildcard', function (t) {324    t.plan(2);325    var evtstring = "event-test";326    // Construct the invoke request327    var invokeRequest = {328        // Name (hash) required for invoke329        chaincodeID: testChaincodeID,330        // Function to trigger331        fcn: "invoke",332        // Parameters for the invoke function333        args: [evtstring]334    };335    var eh = chain.getEventHub();336    var duration = chain.getInvokeWaitTime() * 1000;337    var timedout = true;338    var timeoutId = null;339    // register for chaincode event with wildcard event name340    var regid = eh.registerChaincodeEvent(testChaincodeID, ".*", function(event) {341        timedout = false;342        if (timeoutId) {343            clearTimeout(timeoutId);344        }345        t.equal(event.payload.toString(), "Event 2," + evtstring, "Successfully received expected chaincode event payload");346        eh.unregisterChaincodeEvent(regid);347    });348    // Trigger the invoke transaction349    var invokeTx = test_user_Member1.invoke(invokeRequest);350    // set timout on event sent by chaincode invoke351    timeoutId = setTimeout(function() {352                                 if(timedout) {353                                     eh.unregisterChaincodeEvent(regid);354                                     t.fail("Failed to receive chaincode event");355                                     process.exit(1);356                                 }357                             },358                             duration);359    // Print the invoke results360    invokeTx.on('complete', function (results) {361        // Invoke transaction submitted successfully362        t.pass(util.format("Successfully completed chaincode invoke transaction: request=%j, response=%j", invokeRequest, results));363    });364    invokeTx.on('error', function (err) {365        // Invoke transaction submission failed366        t.fail(util.format("Failed to submit chaincode invoke transaction: request=%j, error=%j", invokeRequest, err));367        // Exit the test script after a failure368        process.exit(1);369    });370});371//372// Issue a chaincode invoke to generate event and listen for the event373// by registering with chaincode id and a bogus event name374//375test('Generate an event that fails to be received', function (t) {376    t.plan(2);377    var evtstring = "event-test";378    // Construct the invoke request379    var invokeRequest = {380        // Name (hash) required for invoke381        chaincodeID: testChaincodeID,382        // Function to trigger383        fcn: "invoke",384        // Parameters for the invoke function385        args: [evtstring]386    };387    var eh = chain.getEventHub();388    var duration = chain.getInvokeWaitTime() * 1000;389    var timedout = true;390    var timeoutId = null;391    // register for chaincode event with bogus event name392    var regid = eh.registerChaincodeEvent(testChaincodeID, "bogus", function(event) {393        timedout = false;394        if (timeoutId) {395            clearTimeout(timeoutId);396        }397        t.fail("Received chaincode event from bogus registration");398        eh.unregisterChaincodeEvent(regid);399        process.exit(1);400    });401    // Trigger the invoke transaction402    var invokeTx = test_user_Member1.invoke(invokeRequest);403    // set timout on event sent by chaincode invoke404    timeoutId = setTimeout(function() {405                                 if(timedout) {406                                     eh.unregisterChaincodeEvent(regid);407                                     t.pass("Failed to receive chaincode event");408                                 }409                             },410                             duration);411    // Print the invoke results412    invokeTx.on('complete', function (results) {413        // Invoke transaction submitted successfully414        t.pass(util.format("Successfully completed chaincode invoke transaction: request=%j, response=%j", invokeRequest, results));415    });416    invokeTx.on('error', function (err) {...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
