Best JavaScript code snippet using mountebank
UnifiedComplete.js
Source:UnifiedComplete.js
...581 582 let queries = [ this._adaptiveQuery ];583 584 585 if (this.hasBehavior("openpage")) {586 queries.push(this._switchToTabQuery);587 }588 queries.push(this._searchQuery);589 590 591 592 593 594 let hasFirstResult = false;595 if (this._searchTokens.length > 0) {596 597 hasFirstResult = yield this._matchPlacesKeyword();598 }599 if (this.pending && this._enableActions && !hasFirstResult) {600 601 602 hasFirstResult = yield this._matchSearchEngineAlias();603 }604 let shouldAutofill = this._shouldAutofill;605 if (this.pending && !hasFirstResult && shouldAutofill) {606 607 hasFirstResult = yield this._matchKnownUrl(conn);608 }609 if (this.pending && !hasFirstResult && shouldAutofill) {610 611 hasFirstResult = yield this._matchSearchEngineUrl();612 }613 if (this.pending && this._enableActions && !hasFirstResult) {614 615 616 617 618 619 620 hasFirstResult = yield this._matchUnknownUrl();621 }622 if (this.pending && this._enableActions && !hasFirstResult) {623 624 hasFirstResult = yield this._matchCurrentSearchEngine();625 }626 627 yield this._sleep(Prefs.delay);628 if (!this.pending)629 return;630 yield this._matchSearchSuggestions();631 if (!this.pending)632 return;633 for (let [query, params] of queries) {634 yield conn.executeCached(query, params, this._onResultRow.bind(this));635 if (!this.pending)636 return;637 }638 639 640 641 if (this._matchBehavior == MATCH_BOUNDARY_ANYWHERE &&642 this._localMatchesCount < Prefs.maxRichResults) {643 this._matchBehavior = MATCH_ANYWHERE;644 for (let [query, params] of [ this._adaptiveQuery,645 this._searchQuery ]) {646 yield conn.executeCached(query, params, this._onResultRow.bind(this));647 if (!this.pending)648 return;649 }650 }651 652 yield Promise.all(this._remoteMatchesPromises);653 }),654 *_matchSearchSuggestions() {655 if (!this.hasBehavior("searches") || this._inPrivateWindow) {656 return;657 }658 this._searchSuggestionController =659 PlacesSearchAutocompleteProvider.getSuggestionController(660 this._searchTokens.join(" "),661 this._inPrivateWindow,662 Prefs.maxRichResults663 );664 let promise = this._searchSuggestionController.fetchCompletePromise665 .then(() => {666 while (this.pending && this._remoteMatchesCount < Prefs.maxRichResults) {667 let [match, suggestion] = this._searchSuggestionController.consume();668 if (!suggestion)669 break;670 671 let searchString = this._searchTokens.join(" ");672 this._addSearchEngineMatch(match, searchString, suggestion);673 }674 });675 if (this.hasBehavior("restrict")) {676 677 yield promise;678 this.stop();679 } else {680 this._remoteMatchesPromises.push(promise);681 }682 },683 _matchKnownUrl: function* (conn) {684 685 let lastSlashIndex = this._searchString.lastIndexOf("/");686 687 if (lastSlashIndex != -1) {688 689 if (lastSlashIndex < this._searchString.length - 1) {690 691 692 693 694 695 let gotResult = false;696 let [ query, params ] = this._urlQuery;697 yield conn.executeCached(query, params, row => {698 gotResult = true;699 this._onResultRow(row);700 });701 return gotResult;702 }703 return false;704 }705 let gotResult = false;706 let [ query, params ] = this._hostQuery;707 yield conn.executeCached(query, params, row => {708 gotResult = true;709 this._onResultRow(row);710 });711 return gotResult;712 },713 _matchPlacesKeyword: function* () {714 715 let keyword = this._searchTokens[0];716 let entry = yield PlacesUtils.keywords.fetch(this._searchTokens[0]);717 if (!entry)718 return false;719 720 let searchString = this._trimmedOriginalSearchString;721 let queryString = "";722 let queryIndex = searchString.indexOf(" ");723 if (queryIndex != -1) {724 queryString = searchString.substring(queryIndex + 1);725 }726 727 queryString = encodeURIComponent(queryString).replace(/%20/g, "+");728 let escapedURL = entry.url.href.replace("%s", queryString);729 let style = (this._enableActions ? "action " : "") + "keyword";730 let actionURL = makeActionURL("keyword", { url: escapedURL,731 input: this._originalSearchString });732 let value = this._enableActions ? actionURL : escapedURL;733 734 let comment = entry.url.host;735 this._addMatch({ value, comment, style, frecency: FRECENCY_DEFAULT });736 return true;737 },738 _matchSearchEngineUrl: function* () {739 if (!Prefs.autofillSearchEngines)740 return false;741 let match = yield PlacesSearchAutocompleteProvider.findMatchByToken(742 this._searchString);743 if (!match)744 return false;745 746 747 748 749 750 751 752 try {753 let prefixURI = NetUtil.newURI(this._strippedPrefix);754 let finalURI = NetUtil.newURI(match.url);755 if (prefixURI.scheme != finalURI.scheme)756 return false;757 } catch (e) {}758 759 760 if (this._strippedPrefix.endsWith("www.") &&761 !stripHttpAndTrim(match.url).startsWith("www."))762 return false;763 let value = this._strippedPrefix + match.token;764 765 766 767 if (!value.startsWith(this._originalSearchString)) {768 Components.utils.reportError(`Trying to inline complete in-the-middle769 ${this._originalSearchString} to ${value}`);770 return false;771 }772 this._result.setDefaultIndex(0);773 this._addMatch({774 value: value,775 comment: match.engineName,776 icon: match.iconUrl,777 style: "priority-search",778 finalCompleteValue: match.url,779 frecency: FRECENCY_DEFAULT780 });781 return true;782 },783 _matchSearchEngineAlias: function* () {784 if (this._searchTokens.length < 2)785 return false;786 let alias = this._searchTokens[0];787 let match = yield PlacesSearchAutocompleteProvider.findMatchByAlias(alias);788 if (!match)789 return false;790 match.engineAlias = alias;791 let query = this._searchTokens.slice(1).join(" ");792 this._addSearchEngineMatch(match, query);793 return true;794 },795 _matchCurrentSearchEngine: function* () {796 let match = yield PlacesSearchAutocompleteProvider.getDefaultMatch();797 if (!match)798 return false;799 let query = this._originalSearchString;800 this._addSearchEngineMatch(match, query);801 return true;802 },803 _addSearchEngineMatch(match, query, suggestion) {804 let actionURLParams = {805 engineName: match.engineName,806 input: suggestion || this._originalSearchString,807 searchQuery: query,808 };809 if (suggestion)810 actionURLParams.searchSuggestion = suggestion;811 if (match.engineAlias) {812 actionURLParams.alias = match.engineAlias;813 }814 let value = makeActionURL("searchengine", actionURLParams);815 this._addMatch({816 value: value,817 comment: match.engineName,818 icon: match.iconUrl,819 style: "action searchengine",820 frecency: FRECENCY_DEFAULT,821 remote: !!suggestion822 });823 },824 825 826 _matchUnknownUrl: function* () {827 let flags = Ci.nsIURIFixup.FIXUP_FLAG_FIX_SCHEME_TYPOS |828 Ci.nsIURIFixup.FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP;829 let fixupInfo = null;830 try {831 fixupInfo = Services.uriFixup.getFixupURIInfo(this._originalSearchString,832 flags);833 } catch (e) {834 return false;835 }836 837 838 839 840 841 if (!fixupInfo.fixedURI || fixupInfo.keywordAsSent)842 return false;843 let uri = fixupInfo.fixedURI;844 845 846 847 848 let hostExpected = new Set(["http", "https", "ftp", "chrome", "resource"]);849 if (hostExpected.has(uri.scheme) && !uri.host)850 return false;851 852 853 if (uri.asciiHost &&854 REGEXP_SINGLEWORD_HOST.test(uri.asciiHost) &&855 !Services.uriFixup.isDomainWhitelisted(uri.asciiHost, -1)) {856 return false;857 }858 let value = makeActionURL("visiturl", {859 url: uri.spec,860 input: this._originalSearchString,861 });862 let match = {863 value: value,864 comment: uri.spec,865 style: "action visiturl",866 frecency: 0,867 };868 try {869 let favicon = yield PlacesUtils.promiseFaviconLinkUrl(uri);870 if (favicon)871 match.icon = favicon.spec;872 } catch (e) {873 874 };875 this._addMatch(match);876 return true;877 },878 _onResultRow: function (row) {879 TelemetryStopwatch.finish(TELEMETRY_1ST_RESULT, this);880 let queryType = row.getResultByIndex(QUERYINDEX_QUERYTYPE);881 let match;882 switch (queryType) {883 case QUERYTYPE_AUTOFILL_HOST:884 this._result.setDefaultIndex(0);885 match = this._processHostRow(row);886 break;887 case QUERYTYPE_AUTOFILL_URL:888 this._result.setDefaultIndex(0);889 match = this._processUrlRow(row);890 break;891 case QUERYTYPE_FILTERED:892 match = this._processRow(row);893 break;894 }895 this._addMatch(match);896 897 898 if (!this.pending || this._localMatchesCount == Prefs.maxRichResults)899 throw StopIteration;900 },901 _maybeRestyleSearchMatch: function (match) {902 903 let parseResult =904 PlacesSearchAutocompleteProvider.parseSubmissionURL(match.value);905 if (!parseResult) {906 return;907 }908 909 910 911 912 let terms = parseResult.terms.toLowerCase();913 if (this._searchTokens.length > 0 &&914 this._searchTokens.every(token => terms.indexOf(token) == -1)) {915 return;916 }917 918 match.style = "search " + match.style;919 match.comment = parseResult.terms + TITLE_SEARCH_ENGINE_SEPARATOR +920 parseResult.engineName;921 },922 _addMatch(match) {923 924 925 if (!this.pending)926 return;927 928 let urlMapKey = stripHttpAndTrim(match.value);929 if ((match.placeId && this._usedPlaceIds.has(match.placeId)) ||930 this._usedURLs.has(urlMapKey)) {931 return;932 }933 934 935 936 937 938 939 if (match.placeId)940 this._usedPlaceIds.add(match.placeId);941 this._usedURLs.add(urlMapKey);942 match.style = match.style || "favicon";943 944 if (Prefs.restyleSearches && match.style == "favicon") {945 this._maybeRestyleSearchMatch(match);946 }947 match.icon = match.icon || PlacesUtils.favicons.defaultFavicon.spec;948 match.finalCompleteValue = match.finalCompleteValue || "";949 this._result.insertMatchAt(this._getInsertIndexForMatch(match),950 match.value,951 match.comment,952 match.icon,953 match.style,954 match.finalCompleteValue);955 if (this._result.matchCount == 6)956 TelemetryStopwatch.finish(TELEMETRY_6_FIRST_RESULTS, this);957 this.notifyResults(true);958 },959 _getInsertIndexForMatch(match) {960 let index = 0;961 if (match.remote) {962 963 index = this._remoteMatchesStartIndex + this._remoteMatchesCount;964 this._remoteMatchesCount++;965 } else {966 967 if (match.frecency > FRECENCY_DEFAULT ||968 this._localMatchesCount < MINIMUM_LOCAL_MATCHES) {969 970 index = this._remoteMatchesStartIndex;971 this._remoteMatchesStartIndex++972 } else {973 974 index = this._localMatchesCount + this._remoteMatchesCount;975 }976 this._localMatchesCount++;977 }978 return index;979 },980 _processHostRow: function (row) {981 let match = {};982 let trimmedHost = row.getResultByIndex(QUERYINDEX_URL);983 let untrimmedHost = row.getResultByIndex(QUERYINDEX_TITLE);984 let frecency = row.getResultByIndex(QUERYINDEX_FRECENCY);985 let faviconUrl = row.getResultByIndex(QUERYINDEX_ICONURL);986 987 988 if (untrimmedHost &&989 !untrimmedHost.toLowerCase().includes(this._trimmedOriginalSearchString.toLowerCase())) {990 untrimmedHost = null;991 }992 match.value = this._strippedPrefix + trimmedHost;993 994 match.comment = stripHttpAndTrim(trimmedHost);995 match.finalCompleteValue = untrimmedHost;996 match.icon = faviconUrl;997 998 999 match.frecency = frecency;1000 match.style = "autofill";1001 return match;1002 },1003 _processUrlRow: function (row) {1004 let match = {};1005 let value = row.getResultByIndex(QUERYINDEX_URL);1006 let url = fixupSearchText(value);1007 let frecency = row.getResultByIndex(QUERYINDEX_FRECENCY);1008 let faviconUrl = row.getResultByIndex(QUERYINDEX_ICONURL);1009 let prefix = value.slice(0, value.length - stripPrefix(value).length);1010 1011 let separatorIndex = url.slice(this._searchString.length)1012 .search(/[\/\?\#]/);1013 if (separatorIndex != -1) {1014 separatorIndex += this._searchString.length;1015 if (url[separatorIndex] == "/") {1016 separatorIndex++; 1017 }1018 url = url.slice(0, separatorIndex);1019 }1020 1021 1022 let untrimmedURL = prefix + url;1023 if (untrimmedURL &&1024 !untrimmedURL.toLowerCase().includes(this._trimmedOriginalSearchString.toLowerCase())) {1025 untrimmedURL = null;1026 }1027 match.value = this._strippedPrefix + url;1028 match.comment = url;1029 match.finalCompleteValue = untrimmedURL;1030 match.icon = faviconUrl;1031 1032 1033 match.frecency = frecency;1034 match.style = "autofill";1035 return match;1036 },1037 _processRow: function (row) {1038 let match = {};1039 match.placeId = row.getResultByIndex(QUERYINDEX_PLACEID);1040 let queryType = row.getResultByIndex(QUERYINDEX_QUERYTYPE);1041 let escapedURL = row.getResultByIndex(QUERYINDEX_URL);1042 let openPageCount = row.getResultByIndex(QUERYINDEX_SWITCHTAB) || 0;1043 let historyTitle = row.getResultByIndex(QUERYINDEX_TITLE) || "";1044 let iconurl = row.getResultByIndex(QUERYINDEX_ICONURL) || "";1045 let bookmarked = row.getResultByIndex(QUERYINDEX_BOOKMARKED);1046 let bookmarkTitle = bookmarked ?1047 row.getResultByIndex(QUERYINDEX_BOOKMARKTITLE) : null;1048 let tags = row.getResultByIndex(QUERYINDEX_TAGS) || "";1049 let frecency = row.getResultByIndex(QUERYINDEX_FRECENCY);1050 1051 1052 let url = escapedURL;1053 let action = null;1054 if (this._enableActions && openPageCount > 0 && this.hasBehavior("openpage")) {1055 url = makeActionURL("switchtab", {url: escapedURL});1056 action = "switchtab";1057 }1058 1059 let title = bookmarkTitle || historyTitle;1060 1061 let showTags = !!tags;1062 1063 1064 if (this.hasBehavior("history") && !this.hasBehavior("bookmark") &&1065 !showTags) {1066 showTags = false;1067 match.style = "favicon";1068 }1069 1070 if (showTags) {1071 title += TITLE_TAGS_SEPARATOR + tags;1072 }1073 1074 1075 1076 if (!match.style) {1077 1078 1079 1080 if (showTags) {1081 1082 1083 match.style = this.hasBehavior("bookmark") ? "bookmark-tag" : "tag";1084 }1085 else if (bookmarked) {1086 match.style = "bookmark";1087 }1088 }1089 if (action)1090 match.style = "action " + action;1091 match.value = url;1092 match.comment = title;1093 if (iconurl) {1094 match.icon = PlacesUtils.favicons1095 .getFaviconLinkForIcon(NetUtil.newURI(iconurl)).spec;1096 }1097 match.frecency = frecency;1098 return match;1099 },1100 1101 get _suggestionPrefQuery() {1102 if (!this.hasBehavior("restrict") && this.hasBehavior("history") &&1103 this.hasBehavior("bookmark")) {1104 return this.hasBehavior("typed") ? defaultQuery("AND h.typed = 1")1105 : defaultQuery();1106 }1107 let conditions = [];1108 if (this.hasBehavior("history")) {1109 1110 1111 1112 conditions.push("+h.visit_count > 0");1113 }1114 if (this.hasBehavior("typed")) {1115 conditions.push("h.typed = 1");1116 }1117 if (this.hasBehavior("bookmark")) {1118 conditions.push("bookmarked");1119 }1120 if (this.hasBehavior("tag")) {1121 conditions.push("tags NOTNULL");1122 }1123 return conditions.length ? defaultQuery("AND " + conditions.join(" AND "))1124 : defaultQuery();1125 },1126 1127 get _searchQuery() {1128 let query = this._suggestionPrefQuery;1129 return [1130 query,1131 {1132 parent: PlacesUtils.tagsFolderId,1133 query_type: QUERYTYPE_FILTERED,1134 matchBehavior: this._matchBehavior,1135 searchBehavior: this._behavior,1136 1137 1138 searchString: this._searchTokens.join(" "),1139 1140 1141 maxResults: Prefs.maxRichResults1142 }1143 ];1144 },1145 1146 get _switchToTabQuery() [1147 SQL_SWITCHTAB_QUERY,1148 {1149 query_type: QUERYTYPE_FILTERED,1150 matchBehavior: this._matchBehavior,1151 searchBehavior: this._behavior,1152 1153 1154 searchString: this._searchTokens.join(" "),1155 maxResults: Prefs.maxRichResults1156 }1157 ],1158 1159 get _adaptiveQuery() [1160 SQL_ADAPTIVE_QUERY,1161 {1162 parent: PlacesUtils.tagsFolderId,1163 search_string: this._searchString,1164 query_type: QUERYTYPE_FILTERED,1165 matchBehavior: this._matchBehavior,1166 searchBehavior: this._behavior1167 }1168 ],1169 1170 get _shouldAutofill() {1171 1172 if (!Prefs.autofill)1173 return false;1174 if (!this._searchTokens.length == 1)1175 return false;1176 1177 if (!this.hasBehavior("history") &&1178 !this.hasBehavior("bookmark"))1179 return false;1180 1181 if (this.hasBehavior("title") || this.hasBehavior("tag"))1182 return false;1183 1184 1185 1186 1187 if (/\s/.test(this._originalSearchString))1188 return false;1189 if (this._searchString.length == 0)1190 return false;1191 return true;1192 },1193 1194 get _hostQuery() {1195 let typed = Prefs.autofillTyped || this.hasBehavior("typed");1196 let bookmarked = this.hasBehavior("bookmark") && !this.hasBehavior("history");1197 return [1198 bookmarked ? typed ? SQL_BOOKMARKED_TYPED_HOST_QUERY1199 : SQL_BOOKMARKED_HOST_QUERY1200 : typed ? SQL_TYPED_HOST_QUERY1201 : SQL_HOST_QUERY,1202 {1203 query_type: QUERYTYPE_AUTOFILL_HOST,1204 searchString: this._searchString.toLowerCase()1205 }1206 ];1207 },1208 1209 get _urlQuery() {1210 1211 1212 1213 let slashIndex = this._autofillUrlSearchString.indexOf("/");1214 let revHost = this._autofillUrlSearchString.substring(0, slashIndex).toLowerCase()1215 .split("").reverse().join("") + ".";1216 let typed = Prefs.autofillTyped || this.hasBehavior("typed");1217 let bookmarked = this.hasBehavior("bookmark") && !this.hasBehavior("history");1218 return [1219 bookmarked ? typed ? SQL_BOOKMARKED_TYPED_URL_QUERY1220 : SQL_BOOKMARKED_URL_QUERY1221 : typed ? SQL_TYPED_URL_QUERY1222 : SQL_URL_QUERY,1223 {1224 query_type: QUERYTYPE_AUTOFILL_URL,1225 searchString: this._autofillUrlSearchString,1226 revHost1227 }1228 ];1229 },1230 1231 notifyResults: function (searchOngoing) {...
index-spec.ts
Source:index-spec.ts
...13 shouldBegin() {14 return false;15 },16 });17 expect(Behavior.hasBehavior('first-behavior')).toBe(true);18 expect(Behavior.hasBehavior('test')).toBe(false);19 const BehaviorInstance = Behavior.getBehavior('first-behavior');20 const instance = new BehaviorInstance();21 const events = instance.getEvents();22 expect(Object.keys(events)).toEqual(['click']);23 expect(instance.shouldBegin()).toEqual(false);24 });25 it('register multiple behavior', () => {26 Behavior.registerBehavior('first', {27 getEvents() {28 return {29 click: 'onClick',30 'edge:click': 'onEdgeClick',31 contextmenu: 'onContextMenu',32 };33 },34 onClick() {35 return 'onclick';36 },37 onContextMenu() {38 return 'onContextMenu';39 },40 });41 Behavior.registerBehavior('second', {42 getDefaultCfg() {43 return {44 style: {45 fill: 'red',46 },47 };48 },49 getEvents() {50 return {51 drag: 'onDrag',52 };53 },54 onDrag() {55 return 'drag';56 },57 });58 const FirstInstance = Behavior.getBehavior('first');59 const SecondBehavior = Behavior.getBehavior('second');60 const firstInstance = new FirstInstance();61 const secondBehavior = new SecondBehavior();62 expect(firstInstance).not.toBe(undefined);63 expect(secondBehavior).not.toBe(undefined);64 expect(Behavior.getBehavior('three')).toBe(undefined);65 expect(Behavior.hasBehavior('first')).toBe(true);66 expect(Behavior.hasBehavior('three')).toBe(false);67 const config1 = firstInstance.getDefaultCfg();68 expect(config1.style).toBe(undefined);69 const events1 = firstInstance.getEvents();70 expect(Object.keys(events1).length).toEqual(3);71 expect(Object.keys(events1)).toEqual(['click', 'edge:click', 'contextmenu']);72 const config = secondBehavior.getDefaultCfg();73 expect(config.style.fill).toEqual('red');74 expect(config.style.fill).not.toEqual('blue');75 const drag = secondBehavior.onDrag();76 expect(drag).toEqual('drag');77 });78 it('register behavior without object', () => {79 expect(() => {80 Behavior.registerBehavior('first', undefined);...
events1a_review.js
Source:events1a_review.js
1//1. Must have == 1 sprites2var starterSprites = false;3//2. Any sprite must have scale != 1004var changedSize=false;5//3. One sprite must have a behavior6var hasBehavior = false;7//Helper variables8var spriteIds = getSpriteIdsInUse();9var animations = getAnimationsInUse();10var failTime=10;11//Check for sprites12if(spriteIds.length >= 1){13 starterSprites=true;14}15//Check for sprites getting resized16for (var i = 0; i < spriteIds.length; i++) {17 if ((getProp({id: spriteIds[i]}, "scale") != 100)) {18 changedSize = true;19 } 20 }21//Check for behaviors22var currentBehaviors=0;23for (var i = 0; i < animations.length; i++) {24 if(getNumBehaviorsForAnimation(animations[i])>=1){25 hasBehavior=true;26 if(!validationProps.successTime){27 validationProps.successTime=World.frameCount;28 }29 }30}31if (World.frameCount > failTime) {32 // Check criteria and give failure feedback33 if (!starterSprites) {34 levelFailure(3, "noSprites");35 } else if (!changedSize) {36 levelFailure(3, "setSecondSpriteSize");37 } else if (!hasBehavior) {38 levelFailure(3, "noBehavior");39 }40}41//Pass 100 frames after success42var waitTime=150;43if (World.frameCount-validationProps.successTime >= waitTime) {44 console.log("Explore success");45 levelFailure(0, "genericExplore");46 }47push();48var array=getBehaviorsForSpriteId(spriteIds[0]);49if(array.length===0){50 array=["none"];51}52textAlign(LEFT, TOP);53textSize(20);54noStroke();55text("Current Behaviors:",10,25);56for(var i=0;i<array.length;i++){57 text(array[i],10,50+i*25);58}59pop();60//timer61if(!starterSprites||!hasBehavior||!changedSize){62 fill(rgb(118,102,160));63 rect(0,390,(World.frameCount*400/failTime),10);64} else {65 fill(rgb(0,173,188));66 rect(0,390,(World.frameCount*400/waitTime),10);...
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!!