Best JavaScript code snippet using mountebank
DataView.js
Source:DataView.js
1var util = require('./util');2var DataSet = require('./DataSet');3/**4 * DataView5 *6 * a dataview offers a filtered view on a dataset or an other dataview.7 *8 * @param {DataSet | DataView} data9 * @param {Object} [options] Available options: see method get10 *11 * @constructor DataView12 */13function DataView (data, options) {14 this._data = null;15 this._ids = {}; // ids of the items currently in memory (just contains a boolean true)16 this.length = 0; // number of items in the DataView17 this._options = options || {};18 this._fieldId = 'id'; // name of the field containing id19 this._subscribers = {}; // event subscribers20 var me = this;21 this.listener = function () {22 me._onEvent.apply(me, arguments);23 };24 this.setData(data);25}26// TODO: implement a function .config() to dynamically update things like configured filter27// and trigger changes accordingly28/**29 * Set a data source for the view30 * @param {DataSet | DataView} data31 */32DataView.prototype.setData = function (data) {33 var ids, id, i, len, items;34 if (this._data) {35 // unsubscribe from current dataset36 if (this._data.off) {37 this._data.off('*', this.listener);38 }39 // trigger a remove of all items in memory40 ids = this._data.getIds({filter: this._options && this._options.filter});41 items = [];42 for (i = 0, len = ids.length; i < len; i++) {43 items.push(this._data._data[ids[i]]);44 }45 this._ids = {};46 this.length = 0;47 this._trigger('remove', {items: ids, oldData: items});48 }49 this._data = data;50 if (this._data) {51 // update fieldId52 this._fieldId = this._options.fieldId ||53 (this._data && this._data.options && this._data.options.fieldId) ||54 'id';55 // trigger an add of all added items56 ids = this._data.getIds({filter: this._options && this._options.filter});57 for (i = 0, len = ids.length; i < len; i++) {58 id = ids[i];59 this._ids[id] = true;60 }61 this.length = ids.length;62 this._trigger('add', {items: ids});63 // subscribe to new dataset64 if (this._data.on) {65 this._data.on('*', this.listener);66 }67 }68};69/**70 * Refresh the DataView. Useful when the DataView has a filter function71 * containing a variable parameter.72 */73DataView.prototype.refresh = function () {74 var id, i, len;75 var ids = this._data.getIds({filter: this._options && this._options.filter}),76 oldIds = Object.keys(this._ids),77 newIds = {},78 addedIds = [],79 removedIds = [],80 removedItems = [];81 // check for additions82 for (i = 0, len = ids.length; i < len; i++) {83 id = ids[i];84 newIds[id] = true;85 if (!this._ids[id]) {86 addedIds.push(id);87 this._ids[id] = true;88 }89 }90 // check for removals91 for (i = 0, len = oldIds.length; i < len; i++) {92 id = oldIds[i];93 if (!newIds[id]) {94 removedIds.push(id);95 removedItems.push(this._data._data[id]);96 delete this._ids[id];97 }98 }99 this.length += addedIds.length - removedIds.length;100 // trigger events101 if (addedIds.length) {102 this._trigger('add', {items: addedIds});103 }104 if (removedIds.length) {105 this._trigger('remove', {items: removedIds, oldData: removedItems});106 }107};108/**109 * Get data from the data view110 *111 * Usage:112 *113 * get()114 * get(options: Object)115 * get(options: Object, data: Array | DataTable)116 *117 * get(id: Number)118 * get(id: Number, options: Object)119 * get(id: Number, options: Object, data: Array | DataTable)120 *121 * get(ids: Number[])122 * get(ids: Number[], options: Object)123 * get(ids: Number[], options: Object, data: Array | DataTable)124 *125 * Where:126 *127 * {number | string} id The id of an item128 * {number[] | string{}} ids An array with ids of items129 * {Object} options An Object with options. Available options:130 * {string} [type] Type of data to be returned. Can131 * be 'DataTable' or 'Array' (default)132 * {Object.<string, string>} [convert]133 * {string[]} [fields] field names to be returned134 * {function} [filter] filter items135 * {string | function} [order] Order the items by136 * a field name or custom sort function.137 * {Array | DataTable} [data] If provided, items will be appended to this138 * array or table. Required in case of Google139 * DataTable.140 * @param {Array} args141 * @return {DataSet|DataView}142 */143DataView.prototype.get = function (args) { // eslint-disable-line no-unused-vars144 var me = this;145 // parse the arguments146 var ids, options, data;147 var firstType = util.getType(arguments[0]);148 if (firstType == 'String' || firstType == 'Number' || firstType == 'Array') {149 // get(id(s) [, options] [, data])150 ids = arguments[0]; // can be a single id or an array with ids151 options = arguments[1];152 data = arguments[2];153 }154 else {155 // get([, options] [, data])156 options = arguments[0];157 data = arguments[1];158 }159 // extend the options with the default options and provided options160 var viewOptions = util.extend({}, this._options, options);161 // create a combined filter method when needed162 if (this._options.filter && options && options.filter) {163 viewOptions.filter = function (item) {164 return me._options.filter(item) && options.filter(item);165 }166 }167 // build up the call to the linked data set168 var getArguments = [];169 if (ids != undefined) {170 getArguments.push(ids);171 }172 getArguments.push(viewOptions);173 getArguments.push(data);174 return this._data && this._data.get.apply(this._data, getArguments);175};176/**177 * Get ids of all items or from a filtered set of items.178 * @param {Object} [options] An Object with options. Available options:179 * {function} [filter] filter items180 * {string | function} [order] Order the items by181 * a field name or custom sort function.182 * @return {Array.<string|number>} ids183 */184DataView.prototype.getIds = function (options) {185 var ids;186 if (this._data) {187 var defaultFilter = this._options.filter;188 var filter;189 if (options && options.filter) {190 if (defaultFilter) {191 filter = function (item) {192 return defaultFilter(item) && options.filter(item);193 }194 }195 else {196 filter = options.filter;197 }198 }199 else {200 filter = defaultFilter;201 }202 ids = this._data.getIds({203 filter: filter,204 order: options && options.order205 });206 }207 else {208 ids = [];209 }210 return ids;211};212/**213 * Map every item in the dataset.214 * @param {function} callback215 * @param {Object} [options] Available options:216 * {Object.<string, string>} [type]217 * {string[]} [fields] filter fields218 * {function} [filter] filter items219 * {string | function} [order] Order the items by220 * a field name or custom sort function.221 * @return {Object[]} mappedItems222 */223DataView.prototype.map = function (callback,options) {224 var mappedItems = [];225 if (this._data) {226 var defaultFilter = this._options.filter;227 var filter;228 if (options && options.filter) {229 if (defaultFilter) {230 filter = function (item) {231 return defaultFilter(item) && options.filter(item);232 }233 }234 else {235 filter = options.filter;236 }237 }238 else {239 filter = defaultFilter;240 }241 mappedItems = this._data.map(callback,{242 filter: filter,243 order: options && options.order244 });245 }246 else {247 mappedItems = [];248 }249 return mappedItems;250};251/**252 * Get the DataSet to which this DataView is connected. In case there is a chain253 * of multiple DataViews, the root DataSet of this chain is returned.254 * @return {DataSet} dataSet255 */256DataView.prototype.getDataSet = function () {257 var dataSet = this;258 while (dataSet instanceof DataView) {259 dataSet = dataSet._data;260 }261 return dataSet || null;262};263/**264 * Event listener. Will propagate all events from the connected data set to265 * the subscribers of the DataView, but will filter the items and only trigger266 * when there are changes in the filtered data set.267 * @param {string} event268 * @param {Object | null} params269 * @param {string} senderId270 * @private271 */272DataView.prototype._onEvent = function (event, params, senderId) {273 var i, len, id, item;274 var ids = params && params.items;275 var addedIds = [],276 updatedIds = [],277 removedIds = [],278 oldItems = [],279 updatedItems = [],280 removedItems = [];281 if (ids && this._data) {282 switch (event) {283 case 'add':284 // filter the ids of the added items285 for (i = 0, len = ids.length; i < len; i++) {286 id = ids[i];287 item = this.get(id);288 if (item) {289 this._ids[id] = true;290 addedIds.push(id);291 }292 }293 break;294 case 'update':295 // determine the event from the views viewpoint: an updated296 // item can be added, updated, or removed from this view.297 for (i = 0, len = ids.length; i < len; i++) {298 id = ids[i];299 item = this.get(id);300 if (item) {301 if (this._ids[id]) {302 updatedIds.push(id);303 updatedItems.push(params.data[i]);304 oldItems.push(params.oldData[i]);305 }306 else {307 this._ids[id] = true;308 addedIds.push(id);309 }310 }311 else {312 if (this._ids[id]) {313 delete this._ids[id];314 removedIds.push(id);315 removedItems.push(params.oldData[i]);316 }317 else {318 // nothing interesting for me :-(319 }320 }321 }322 break;323 case 'remove':324 // filter the ids of the removed items325 for (i = 0, len = ids.length; i < len; i++) {326 id = ids[i];327 if (this._ids[id]) {328 delete this._ids[id];329 removedIds.push(id);330 removedItems.push(params.oldData[i]);331 }332 }333 break;334 }335 this.length += addedIds.length - removedIds.length;336 if (addedIds.length) {337 this._trigger('add', {items: addedIds}, senderId);338 }339 if (updatedIds.length) {340 this._trigger('update', {items: updatedIds, oldData: oldItems, data: updatedItems}, senderId);341 }342 if (removedIds.length) {343 this._trigger('remove', {items: removedIds, oldData: removedItems}, senderId);344 }345 }346};347// copy subscription functionality from DataSet348DataView.prototype.on = DataSet.prototype.on;349DataView.prototype.off = DataSet.prototype.off;350DataView.prototype._trigger = DataSet.prototype._trigger;351// TODO: make these functions deprecated (replaced with `on` and `off` since version 0.5)352DataView.prototype.subscribe = DataView.prototype.on;353DataView.prototype.unsubscribe = DataView.prototype.off;...
variations.test.js
Source:variations.test.js
1/**2 * Copyright © Magento, Inc. All rights reserved.3 * See COPYING.txt for license details.4 */5define([6 'Magento_ConfigurableProduct/js/variations/variations'7], function (Variations) {8 'use strict';9 describe('Magento_ConfigurableProduct/js/variations/variations', function () {10 var variation;11 beforeEach(function () {12 variation = new Variations();13 variation.source = {14 data: {}15 };16 });17 it('checks that "serializeData" serializes data', function () {18 var matrix = [19 {20 name: 'Product1',21 attributes: 'Color: black',22 price: 10023 },24 {25 name: 'Product2',26 attributes: 'Color: red',27 price: 5028 },29 {30 name: 'Product3',31 attributes: 'Color: white',32 price: 2033 }34 ],35 ids = [1, 2, 3],36 resultMatrix = JSON.stringify(matrix),37 resultIds = JSON.stringify(ids);38 variation.source.data['configurable-matrix'] = matrix;39 variation.source.data['associated_product_ids'] = ids;40 variation.serializeData();41 expect(variation.source.data['configurable-matrix']).toEqual(matrix);42 expect(variation.source.data['associated_product_ids']).toEqual(ids);43 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);44 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);45 });46 it('checks that "serializeData" uses old data if there is no data to serialize', function () {47 var matrix = [48 {49 name: 'Product4',50 attributes: 'Color: grey',51 price: 552 },53 {54 name: 'Product5',55 attributes: 'Color: pink',56 price: 7057 },58 {59 name: 'Product6',60 attributes: 'Color: brown',61 price: 3062 }63 ],64 ids = [4, 5, 6],65 resultMatrix = JSON.stringify(matrix),66 resultIds = JSON.stringify(ids);67 variation.source.data['configurable-matrix-serialized'] = JSON.stringify(matrix);68 variation.source.data['associated_product_ids_serialized'] = JSON.stringify(ids);69 variation.serializeData();70 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);71 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);72 });73 it('checks that "serializeData" works correctly if we have new data to be serialized', function () {74 var matrix = [75 {76 name: 'Product7',77 attributes: 'Color: yellow',78 price: 1079 },80 {81 name: 'Product8',82 attributes: 'Color: green',83 price: 20084 },85 {86 name: 'Product9',87 attributes: 'Color: blue',88 price: 50089 }90 ],91 ids = [7, 8, 9],92 resultMatrix = JSON.stringify(matrix),93 resultIds = JSON.stringify(ids);94 variation.source.data['configurable-matrix'] = matrix;95 variation.source.data['associated_product_ids'] = ids;96 variation.source.data['configurable-matrix-serialized'] = JSON.stringify(['some old data']);97 variation.source.data['associated_product_ids_serialized'] = JSON.stringify(['some old data']);98 variation.serializeData();99 expect(variation.source.data['configurable-matrix']).toEqual(matrix);100 expect(variation.source.data['associated_product_ids']).toEqual(ids);101 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);102 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);103 });104 it('checks that "unserializeData" unserializes data', function () {105 var matrixString = '[{"name":"Small Product","attributes":"Size: small","price":5.5},' +106 '{"name":"Medium Product","attributes":"Size: medium","price":10.99},' +107 '{"name":"Large Product","attributes":"Size: large","price":25}]',108 idString = '[100, 101, 102]',109 resultMatrix = JSON.parse(matrixString),110 resultIds = JSON.parse(idString);111 variation.source.data['configurable-matrix-serialized'] = matrixString;112 variation.source.data['associated_product_ids_serialized'] = idString;113 variation.unserializeData();114 expect(variation.source.data['configurable-matrix-serialized']).toBeUndefined();115 expect(variation.source.data['associated_product_ids_serialized']).toBeUndefined();116 expect(variation.source.data['configurable-matrix']).toEqual(resultMatrix);117 expect(variation.source.data['associated_product_ids']).toEqual(resultIds);118 });119 it('checks that "serializeData" and "unserializeData" give proper result', function () {120 var matrix = [121 {122 name: 'Small Product',123 attributes: 'Size: small',124 price: 5.50125 },126 {127 name: 'Medium Product',128 attributes: 'Size: medium',129 price: 10.99130 },131 {132 name: 'Large Product',133 attributes: 'Size: large',134 price: 25135 }136 ],137 ids = [1, 2, 3],138 resultMatrix = JSON.stringify(matrix),139 resultIds = JSON.stringify(ids);140 variation.source.data['configurable-matrix'] = matrix;141 variation.source.data['associated_product_ids'] = ids;142 variation.serializeData();143 expect(variation.source.data['configurable-matrix']).toEqual(matrix);144 expect(variation.source.data['associated_product_ids']).toEqual(ids);145 expect(variation.source.data['configurable-matrix-serialized']).toEqual(resultMatrix);146 expect(variation.source.data['associated_product_ids_serialized']).toEqual(resultIds);147 variation.unserializeData();148 expect(variation.source.data['configurable-matrix']).toEqual(matrix);149 expect(variation.source.data['associated_product_ids']).toEqual(ids);150 expect(variation.source.data['configurable-matrix-serialized']).toBeUndefined();151 expect(variation.source.data['associated_product_ids_serialized']).toBeUndefined();152 });153 });...
autoScrape.js
Source:autoScrape.js
1/////////////////////////////////////////////////////////////////////2// Auto scrapes Spotify artist data with user determined time interval3/////////////////////////////////////////////////////////////////////4// const inquirer = require('inquirer');5const { Sequelize } = require("sequelize");6const db = require("../models");7const spotify = require("./scrape.js");8/////////////////////////////////////////////9/// Put your sql database password below! ///10/////////////////////////////////////////////11const sequelize = new Sequelize(12 process.env.DB_NAME,13 process.env.DB_USERNAME,14 process.env.DB_PASSWORD,15 {16 host: process.env.HOST,17 dialect: "mysql"18 }19);20// Initial Spotify artist ID determined to begin the auto scraping with related artists21let initialArtistID = "2xvtxDNInKDV4AvGmjw6d1";22// Array idsToDo[] for every spotify artist id you wish to scrape23// these will be used if a scraped artist has no genre tags24// or if all related artists of a scraped artist are already in the database.25// Important: the final location of the array should contain 'done', this location26// will not be used as a scraped Spotify id.27//define idsToDo28let idsToDo = [];29sequelize30 .query("SELECT distinct artistID FROM spotify_db.idstoscrape;", {31 type: sequelize.QueryTypes.SELECT32 })33 .then(function(currentArtistIDs) {34 idsToDo = currentArtistIDs;35 });36console.log(`37 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~38 | « « | Spotify Artist Auto Web Scraper - Using node.js, puppeteer, cheerio, and sequelize | » » |39 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);40async function RecursiveInsertRecord(scrapedata) {41 console.log(`Next Spotify Artist (id: ${scrapedata.artist_ID}) scrapedata:`);42 // Checks if Spotify artist id is empty/undefined43 if (44 !Array.isArray(scrapedata.artist_genres) ||45 !scrapedata.artist_genres.length46 ) {47 console.log(48 `artist_genres of (${scrapedata.artist_name}: ${scrapedata.artist_ID}) is empty.`49 );50 if (!Array.isArray(idsToDo) || !idsToDo.length) {51 // pre-populated id list array is empty52 console.log(`idsToDo[] list is now empty. Scraping is now complete.`);53 } else {54 // pre-populated id list array is not empty55 console.log(56 `Artist genre or city data is "undefined", Moving to next id in idsToDo[] object. --> ${idsToDo[0]}`57 );58 let nextID = idsToDo[0].artistID;59 spotify(idsToDo[0].artistID, RecursiveInsertRecord);60 idsToDo.shift();61 }62 }63 // Will populate sql table if genres are defined64 else {65 // First for loop runs # of times depending on length of Spotify Artist's genre tags66 if (67 typeof scrapedata.cityData === "undefined" ||68 typeof scrapedata.artist_genres === "undefined"69 ) {70 if (!Array.isArray(idsToDo) || !idsToDo.length) {71 // pre-populated id list array is empty72 console.log(`idsToDo[] list is now empty. Scraping is now complete.`);73 } else {74 // pre-populated id list array is not empty75 console.log(76 `Artist genre or city data is "undefined", Moving to next id in idsToDo[] object. --> ${idsToDo[0].artistID}`77 );78 let nextID = idsToDo[0].artistID;79 spotify(idsToDo[0].artistID, RecursiveInsertRecord);80 idsToDo.shift();81 }82 } else {83 for (let j = 0; j < scrapedata.artist_genres.length; j++) {84 // Second for loop runs # of times depending on length of Spotify cityData length85 for (let i = 0; i < scrapedata.cityData.length; i++) {86 let record = {87 artist_ID: scrapedata.artist_ID,88 artist_name: scrapedata.artist_name,89 artist_genres: scrapedata.artist_genres[j],90 country: scrapedata.cityData[i].country,91 city: scrapedata.cityData[i].city,92 listeners: scrapedata.cityData[i].listeners93 };94 await db.Spotify.create(record).then(function(results) {95 // `results` here would be the newly created table with unique artist and location information96 // res.json(results);97 });98 }99 }100 // findRelatedArtistID() finds the remaining related artist ID's,101 findRelatedArtistID(scrapedata.relatedArtistIDs);102 }103 }104}105spotify(initialArtistID, RecursiveInsertRecord);106// function to return related artist ID that has not a duplicate of current artist id's107function findRelatedArtistID(relatedArtistIDs) {108 // Querys the database to find all of the current artist id's we have scraped109 // will be used to avoid duplicates110 sequelize111 .query("SELECT distinct artist_ID FROM spotify_db.spotifies;", {112 type: sequelize.QueryTypes.SELECT113 })114 .then(function(currentArtistIDs) {115 console.log(`Current Spotify artist id's in db`);116 console.log(currentArtistIDs);117 let idsToCheck = relatedArtistIDs;118 for (let i = 0; i < currentArtistIDs.length; i++) {119 // runs n+1 times120 for (let j = 0; j < relatedArtistIDs.length; j++) {121 // runs n times122 // checks if dup123 if (relatedArtistIDs[j].id === currentArtistIDs[i].artist_ID) {124 idsToCheck.splice(j, 1);125 console.log(`Remaining unused id's from Spotify related artist`);126 console.log(idsToCheck);127 }128 }129 }130 // exit for loop131 if (!Array.isArray(idsToCheck) || !idsToCheck.length) {132 // if idsToCheck is empty133 if (!Array.isArray(idsToDo) || !idsToDo.length) {134 // pre-populated id list array is empty135 console.log(`idsToDo[] list is now empty. Scraping is now complete.`);136 } else {137 // pre-populated id list array is not empty138 console.log(139 `idsToCheck is empty. Moving to next id in idsToDo[] object. --> ${idsToDo[0].artistID}`140 );141 console.log(`idsToDo length: ${idsToDo.length}`);142 spotify(idsToDo[0].artistID, RecursiveInsertRecord);143 idsToDo.shift();144 }145 } else {146 // if idsToCheck is not empty147 console.log(148 `Id's remaining are non-duplicates, choosing location 0: ${idsToCheck[0].id}`149 );150 console.log(`idsToDo length: ${idsToDo.length}`);151 spotify(idsToCheck[0].id, RecursiveInsertRecord);152 }153 });...
narrow_unread.js
Source:narrow_unread.js
...28}29function assert_unread_info(expected) {30 assert.deepEqual(narrow_state.get_first_unread_info(), expected);31}32function candidate_ids() {33 return narrow_state._possible_unread_message_ids();34}35run_test("get_unread_ids", () => {36 unread.declare_bankruptcy();37 narrow_state.reset_current_filter();38 let unread_ids;39 let terms;40 const sub = {41 name: "My Stream",42 stream_id: 55,43 };44 const stream_msg = {45 id: 101,46 type: "stream",47 stream_id: sub.stream_id,48 topic: "my topic",49 unread: true,50 mentioned: true,51 mentioned_me_directly: true,52 };53 const private_msg = {54 id: 102,55 type: "private",56 unread: true,57 display_recipient: [{id: alice.user_id}],58 };59 message_store.get = (msg_id) => {60 if (msg_id === stream_msg.id) {61 return stream_msg;62 } else if (msg_id === private_msg.id) {63 return private_msg;64 }65 throw new Error("unexpected id");66 };67 stream_data.add_sub(sub);68 unread_ids = candidate_ids();69 assert.equal(unread_ids, undefined);70 terms = [{operator: "search", operand: "whatever"}];71 set_filter(terms);72 unread_ids = candidate_ids();73 assert.equal(unread_ids, undefined);74 assert_unread_info({flavor: "cannot_compute"});75 terms = [{operator: "bogus_operator", operand: "me@example.com"}];76 set_filter(terms);77 unread_ids = candidate_ids();78 assert.deepEqual(unread_ids, []);79 assert_unread_info({flavor: "not_found"});80 terms = [{operator: "stream", operand: "bogus"}];81 set_filter(terms);82 unread_ids = candidate_ids();83 assert.deepEqual(unread_ids, []);84 terms = [{operator: "stream", operand: sub.name}];85 set_filter(terms);86 unread_ids = candidate_ids();87 assert.deepEqual(unread_ids, []);88 assert_unread_info({flavor: "not_found"});89 unread.process_loaded_messages([stream_msg]);90 unread_ids = candidate_ids();91 assert.deepEqual(unread_ids, [stream_msg.id]);92 assert_unread_info({93 flavor: "found",94 msg_id: stream_msg.id,95 });96 terms = [97 {operator: "stream", operand: "bogus"},98 {operator: "topic", operand: "my topic"},99 ];100 set_filter(terms);101 unread_ids = candidate_ids();102 assert.deepEqual(unread_ids, []);103 terms = [104 {operator: "stream", operand: sub.name},105 {operator: "topic", operand: "my topic"},106 ];107 set_filter(terms);108 unread_ids = candidate_ids();109 assert.deepEqual(unread_ids, [stream_msg.id]);110 terms = [{operator: "is", operand: "mentioned"}];111 set_filter(terms);112 unread_ids = candidate_ids();113 assert.deepEqual(unread_ids, [stream_msg.id]);114 terms = [{operator: "sender", operand: "me@example.com"}];115 set_filter(terms);116 // note that our candidate ids are just "all" ids now117 unread_ids = candidate_ids();118 assert.deepEqual(unread_ids, [stream_msg.id]);119 // this actually does filtering120 assert_unread_info({flavor: "not_found"});121 terms = [{operator: "pm-with", operand: "alice@example.com"}];122 set_filter(terms);123 unread_ids = candidate_ids();124 assert.deepEqual(unread_ids, []);125 unread.process_loaded_messages([private_msg]);126 unread_ids = candidate_ids();127 assert.deepEqual(unread_ids, [private_msg.id]);128 assert_unread_info({129 flavor: "found",130 msg_id: private_msg.id,131 });132 terms = [{operator: "is", operand: "private"}];133 set_filter(terms);134 unread_ids = candidate_ids();135 assert.deepEqual(unread_ids, [private_msg.id]);136 // For a negated search, our candidate ids will be all137 // unread messages, even ones that don't pass the filter.138 terms = [{operator: "is", operand: "private", negated: true}];139 set_filter(terms);140 unread_ids = candidate_ids();141 assert.deepEqual(unread_ids, [stream_msg.id, private_msg.id]);142 terms = [{operator: "pm-with", operand: "bob@example.com"}];143 set_filter(terms);144 unread_ids = candidate_ids();145 assert.deepEqual(unread_ids, []);146 terms = [{operator: "is", operand: "starred"}];147 set_filter(terms);148 unread_ids = candidate_ids();149 assert.deepEqual(unread_ids, []);150 terms = [{operator: "search", operand: "needle"}];151 set_filter(terms);152 assert_unread_info({153 flavor: "cannot_compute",154 });155 narrow_state.reset_current_filter();156 blueslip.expect("error", "unexpected call to get_first_unread_info");157 assert_unread_info({158 flavor: "cannot_compute",159 });160});161run_test("defensive code", (override) => {162 // Test defensive code. We actually avoid calling...
index.js
Source:index.js
1import { OPERATIONS_IDS } from 'echojs-lib';2import transformTransferOperations from './specifics.ops/transfer';3import transformAccountOperations from './specifics.ops/account';4import transformAssetOperations from './specifics.ops/asset';5import transformProposalOperations from './specifics.ops/proposal';6import transformCommitteeOperations from './specifics.ops/committee';7import transformVestingOperations from './specifics.ops/vesting.balance';8import transformContractOperations from './specifics.ops/contract';9import transformSidechainOperations from './specifics.ops/sidechain';10import transformDidOperations from './specifics.ops/did';11export const transformOperationDataByType = async (opNumber, data) => {12 switch (opNumber) {13 case OPERATIONS_IDS.TRANSFER:14 case OPERATIONS_IDS.TRANSFER_TO_ADDRESS:15 case OPERATIONS_IDS.OVERRIDE_TRANSFER:16 return transformTransferOperations(opNumber, data);17 case OPERATIONS_IDS.ACCOUNT_CREATE:18 case OPERATIONS_IDS.ACCOUNT_UPDATE:19 case OPERATIONS_IDS.ACCOUNT_WHITELIST:20 case OPERATIONS_IDS.ACCOUNT_ADDRESS_CREATE:21 case OPERATIONS_IDS.EVM_ADDRESS_REGISTER:22 case OPERATIONS_IDS.BLOCK_REWARD:23 return transformAccountOperations(opNumber, data);24 case OPERATIONS_IDS.ASSET_CREATE:25 case OPERATIONS_IDS.ASSET_UPDATE:26 case OPERATIONS_IDS.ASSET_UPDATE_BITASSET:27 case OPERATIONS_IDS.ASSET_UPDATE_FEED_PRODUCERS:28 case OPERATIONS_IDS.ASSET_ISSUE:29 case OPERATIONS_IDS.ASSET_RESERVE:30 case OPERATIONS_IDS.ASSET_FUND_FEE_POOL:31 case OPERATIONS_IDS.ASSET_PUBLISH_FEED:32 case OPERATIONS_IDS.ASSET_CLAIM_FEES:33 return transformAssetOperations(opNumber, data);34 case OPERATIONS_IDS.PROPOSAL_CREATE:35 case OPERATIONS_IDS.PROPOSAL_UPDATE:36 case OPERATIONS_IDS.PROPOSAL_DELETE:37 return transformProposalOperations(opNumber, data);38 case OPERATIONS_IDS.COMMITTEE_MEMBER_CREATE:39 case OPERATIONS_IDS.COMMITTEE_MEMBER_UPDATE:40 case OPERATIONS_IDS.COMMITTEE_MEMBER_UPDATE_GLOBAL_PARAMETERS:41 case OPERATIONS_IDS.COMMITTEE_MEMBER_ACTIVATE:42 case OPERATIONS_IDS.COMMITTEE_MEMBER_DEACTIVATE:43 case OPERATIONS_IDS.COMMITTEE_FROZEN_BALANCE_DEPOSIT:44 case OPERATIONS_IDS.COMMITTEE_FROZEN_BALANCE_WITHDRAW:45 return transformCommitteeOperations(opNumber, data);46 case OPERATIONS_IDS.VESTING_BALANCE_CREATE:47 case OPERATIONS_IDS.VESTING_BALANCE_WITHDRAW:48 case OPERATIONS_IDS.BALANCE_CLAIM:49 case OPERATIONS_IDS.BALANCE_FREEZE:50 case OPERATIONS_IDS.BALANCE_UNFREEZE:51 case OPERATIONS_IDS.REQUEST_BALANCE_UNFREEZE:52 return transformVestingOperations(opNumber, data);53 case OPERATIONS_IDS.CONTRACT_CREATE:54 case OPERATIONS_IDS.CONTRACT_CALL:55 case OPERATIONS_IDS.CONTRACT_INTERNAL_CREATE:56 case OPERATIONS_IDS.CONTRACT_INTERNAL_CALL:57 case OPERATIONS_IDS.CONTRACT_SELFDESTRUCT:58 case OPERATIONS_IDS.CONTRACT_UPDATE:59 case OPERATIONS_IDS.CONTRACT_FUND_POOL:60 case OPERATIONS_IDS.CONTRACT_WHITELIST:61 return transformContractOperations(opNumber, data);62 case OPERATIONS_IDS.SIDECHAIN_ETH_CREATE_ADDRESS:63 case OPERATIONS_IDS.SIDECHAIN_ETH_APPROVE_ADDRESS:64 case OPERATIONS_IDS.SIDECHAIN_ETH_DEPOSIT:65 case OPERATIONS_IDS.SIDECHAIN_ETH_SEND_DEPOSIT:66 case OPERATIONS_IDS.SIDECHAIN_ERC20_APPROVE_TOKEN_WITHDRAW:67 case OPERATIONS_IDS.SIDECHAIN_ERC20_ISSUE:68 case OPERATIONS_IDS.SIDECHAIN_ERC20_BURN:69 case OPERATIONS_IDS.SIDECHAIN_ETH_WITHDRAW:70 case OPERATIONS_IDS.SIDECHAIN_ETH_SEND_WITHDRAW:71 case OPERATIONS_IDS.SIDECHAIN_ETH_APPROVE_WITHDRAW:72 case OPERATIONS_IDS.SIDECHAIN_ETH_UPDATE_CONTRACT_ADDRESS:73 case OPERATIONS_IDS.SIDECHAIN_ISSUE:74 case OPERATIONS_IDS.SIDECHAIN_BURN:75 case OPERATIONS_IDS.SIDECHAIN_ERC20_REGISTER_TOKEN:76 case OPERATIONS_IDS.SIDECHAIN_ERC20_DEPOSIT_TOKEN:77 case OPERATIONS_IDS.SIDECHAIN_ERC20_SEND_DEPOSIT_TOKEN:78 case OPERATIONS_IDS.SIDECHAIN_ERC20_WITHDRAW_TOKEN:79 case OPERATIONS_IDS.SIDECHAIN_ERC20_SEND_WITHDRAW_TOKEN:80 case OPERATIONS_IDS.SIDECHAIN_BTC_CREATE_ADDRESS:81 case OPERATIONS_IDS.SIDECHAIN_BTC_CREATE_INTERMEDIATE_DEPOSIT:82 case OPERATIONS_IDS.SIDECHAIN_BTC_INTERMEDIATE_DEPOSIT:83 case OPERATIONS_IDS.SIDECHAIN_BTC_DEPOSIT:84 case OPERATIONS_IDS.SIDECHAIN_BTC_WITHDRAW:85 case OPERATIONS_IDS.SIDECHAIN_BTC_AGGREGATE:86 case OPERATIONS_IDS.SIDECHAIN_BTC_APPROVE_AGGREGATE:87 case OPERATIONS_IDS.SIDECHAIN_STAKE_ETH_UPDATE:88 case OPERATIONS_IDS.SIDECHAIN_BTC_CREATE_STAKE_SCRIPT:89 case OPERATIONS_IDS.SIDECHAIN_STAKE_BTC_UPDATE:90 case OPERATIONS_IDS.SIDECHAIN_ETH_SPV_CREATE:91 case OPERATIONS_IDS.SIDECHAIN_ETH_SPV_ADD_MISSED_TX_RECEIPT:92 case OPERATIONS_IDS.SIDECHAIN_BTC_SPV_CREATE:93 case OPERATIONS_IDS.SIDECHAIN_BTC_SPV_ADD_MISSED_TX_RECEIPT:94 case OPERATIONS_IDS.SIDECHAIN_SPV_EXCHANGE_EXCESS_FUNDS:95 case OPERATIONS_IDS.SIDECHAIN_ERC20_REGISTER_CONTRACT_OPERATION:96 case OPERATIONS_IDS.SIDECHAIN_ERC20_TRANSFER_ASSET:97 return transformSidechainOperations(opNumber, data);98 case OPERATIONS_IDS.DID_CREATE_OPERATION:99 case OPERATIONS_IDS.DID_UPDATE_OPERATION:100 case OPERATIONS_IDS.DID_DELETE_OPERATION:101 return transformDidOperations(opNumber, data);102 default:103 return transformTransferOperations(0, data);104 }...
Arbitraries.ts
Source:Arbitraries.ts
1import { Gene, TestUniverse } from '@ephox/boss';2import { Arr } from '@ephox/katamari';3import Jsc from '@ephox/wrap-jsverify';4const getIds = function (item: Gene, predicate: (g: Gene) => boolean): string[] {5 const rest = Arr.bind(item.children || [], function (id) { return getIds(id, predicate); });6 const self = predicate(item) && item.id !== 'root' ? [ item.id ] : [];7 return self.concat(rest);8};9const textIds = function (universe: TestUniverse) {10 return getIds(universe.get(), universe.property().isText);11};12export interface ArbTextIds {13 startId: string;14 textIds: string[];15}16const arbTextIds = function (universe: TestUniverse) {17 const ids = textIds(universe);18 return Jsc.elements(textIds(universe)).smap(function (id: string): ArbTextIds {19 return {20 startId: id,21 textIds: ids22 };23 }, function (obj: ArbTextIds) {24 return obj.startId;25 });26};27export interface ArbIds {28 startId: string;29 ids: string[];30}31const arbIds = function (universe: TestUniverse, predicate: (g: Gene) => boolean) {32 const ids = getIds(universe.get(), predicate);33 return Jsc.elements(ids).smap(function (id: string): ArbIds {34 return {35 startId: id,36 ids37 };38 }, function (obj: ArbIds) {39 return obj.startId;40 }, function (obj: ArbIds) {41 return '[id :: ' + obj.startId + ']';42 });43};44export interface ArbRangeIds {45 startId: string;46 finishId: string;47 ids: string[];48}49const arbRangeIds = function (universe: TestUniverse, predicate: (g: Gene) => boolean) {50 const ids = getIds(universe.get(), predicate);51 const generator = Jsc.integer(0, ids.length - 1).generator.flatMap(function (startIndex: number) {52 return Jsc.integer(startIndex, ids.length - 1).generator.map(function (finishIndex: number): ArbRangeIds {53 return {54 startId: ids[startIndex],55 finishId: ids[finishIndex],56 ids57 };58 });59 });60 return Jsc.bless({61 generator62 });63};...
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 {4 {5 is: {6 }7 }8 }9};10mb.create(imposter).then
Using AI Code Generation
1var mb = require('mountebank');2 {3 {4 {5 "is": {6 }7 }8 }9 }10];11mb.create({ port: 2525, pidfile: "mb.pid", logfile: "mb.log" }, imposters)12 .then(function () {13 console.log("mountebank started");14 }, function (error) {15 console.log("error starting mountebank", error);16 });17mb.start({ port: 2525, pidfile: "mb.pid", logfile: "mb.log" }, imposters)18 .then(function () {19 console.log("mountebank started");20 }, function (error) {21 console.log("error starting mountebank", error);22 });23mb.stop({ port: 2525, pidfile: "mb.pid", logfile: "mb.log" }, imposters)24 .then(function () {25 console.log("mountebank started");26 }, function (error) {27 console.log("error starting mountebank", error);28 });29mb.del({ port: 2525, pidfile: "mb.pid", logfile: "mb.log" }, imposters)30 .then(function () {31 console.log("mountebank started");32 }, function (error) {33 console.log("error starting mountebank", error);34 });35mb.reset({ port: 2525, pidfile: "mb.pid", logfile: "mb.log" }, imposters)36 .then(function () {37 console.log("mountebank started");38 }, function (error) {39 console.log("error starting mountebank", error);40 });41mb.verify({ port: 2525, pidfile: "mb.pid", logfile: "mb.log" }, imposters)42 .then(function () {43 console.log("mountebank started");44 }, function (error) {45 console.log("error starting
Using AI Code Generation
1var mb = require('mountebank');2var imposter = mb.create({3 stubs: [{4 responses: [{5 is: {6 headers: {7 },8 }9 }]10 }]11});12imposter.then(function (imposter) {13 console.log('Imposter created at %s', imposter.url);14 imposter.addStub({15 responses: [{16 is: {17 headers: {18 },19 }20 }]21 });22});23var mb = require('mountebank');24var imposter = mb.create({25 stubs: [{26 predicates: [{27 equals: {28 }29 }],30 responses: [{31 is: {32 headers: {33 },34 }35 }]36 }]37});38imposter.then(function (imposter) {39 console.log('Imposter created at %s', imposter.url);40 imposter.addStub({41 predicates: [{42 equals: {43 }44 }],45 responses: [{46 is: {47 headers: {48 },49 }50 }]51 });52});53var mb = require('mountebank');54var imposter = mb.create({55 stubs: [{56 predicates: [{57 equals: {58 }59 }],60 responses: [{61 is: {62 headers: {63 },64 }65 }]66 }]67});68imposter.then(function (imposter) {69 console.log('Imposter created at %s', imposter.url);
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3 {4 {5 {6 equals: {7 }8 }9 {10 is: {11 headers: {12 },13 }14 }15 },16 {17 {18 equals: {19 }20 }21 {22 is: {23 headers: {24 },25 }26 }27 }28 }29];30mb.start({ port: port, pidfile: 'mb.pid', logfile: 'mb.log' }, () => {31 mb.createImposter(2525, imposters[0], () => {32 console.log('Imposter 1 created');33 });34 mb.createImposter(2525, imposters[1], () => {35 console.log('Imposter 2 created');36 });37});38const mb = require('mountebank');39const port = 2525;40 {41 {42 {43 equals: {44 }45 }46 {47 is: {48 headers: {49 },50 }51 }52 },53 {54 {55 equals: {56 }57 }58 {59 is: {60 headers: {61 },62 }63 }64 }65 }66];67mb.start({ port: port
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var server = mb.create({port: port});4server.start().then(function () {5 return server.post('/imposters', {6 stubs: [{7 {8 is: {9 headers: {10 },11 body: JSON.stringify({12 })13 }14 }15 }]16 });17}).then(function (imposter) {18 console.log("imposter is ", imposter);19 console.log('JSON Server is running');20}).catch(function (error) {21 console.error('Error starting server', error);22 process.exit(1);23});24var mb = require('mountebank');25var port = 2525;26var server = mb.create({port: port});27server.start().then(function () {28 return server.post('/imposters', {29 stubs: [{30 {31 is: {32 headers: {33 },34 body: JSON.stringify({35 })36 }37 }38 }]39 });40}).then(function (imposter) {41 console.log("imposter is ", imposter);42 console.log('JSON Server is running');43}).catch(function (error) {44 console.error('Error starting server', error);45 process.exit(1);46});47var mb = require('mountebank');48var port = 2525;49var server = mb.create({port: port});50server.start().then(function () {51 return server.post('/imposters', {52 stubs: [{53 {54 is: {55 headers: {56 },
Using AI Code Generation
1var mb = require('mountebank');2mb.start({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto'}, function () {3 console.log('Mountebank server started');4 var stub = {5 {6 is: {7 headers: {8 },9 body: JSON.stringify({10 })11 }12 }13 };14 var predicate = {15 equals: {16 }17 };18 var imposter = {19 };20 mb.createImposter(3000, imposter, function (error, imposter) {21 console.log('Imposter created');22 var request = {23 headers: {24 }25 };26 mb.sendRequest(3000, request, function (error, response) {27 console.log('Response received');28 console.log(response.body);29 mb.stop(function () {30 console.log('Mountebank server stopped');31 });32 });33 });34});35mb.stop(function () {36 console.log('Mountebank server stopped');37});38mb.start({port: 2525, pidfile: 'mb.pid', logfile: 'mb.log', protofile: 'mb.proto'}, function () {39 console.log('Mountebank server started');40 var stub = {41 {42 is: {43 headers: {44 },45 body: JSON.stringify({
Using AI Code Generation
1const mb = require('mountebank');2const { createImposter, createStub } = require('mountebank/src/models/imposter');3const { createResponse } = require('mountebank/src/models/response');4const { createPredicate } = require('mountebank/src/models/predicate');5const { createRequest } = require('mountebank/src/models/request');6const { createProxyResponse } = require('mountebank/src/models/proxyResponse');7const { createProxy } = require('mountebank/src/models/proxy');8const { createTcpProxyResponse } = require('mountebank/src/models/tcpProxyResponse');9const { createTcpProxy } = require('mountebank/src/models/tcpProxy');10const { createTcpResponse } = require('mountebank/src/models/tcpResponse');11const { createTcpStub } = require('mountebank/src/models/tcpStub');12const { createTcpRequest } = require('mountebank/src/models/tcpRequest');13const { createTcpPredicate } = require('mountebank/src/models/tcpPredicate');14const { createTcpImposter } = require('mountebank/src/models/tcpImposter');15const { createHttpsImposter } = require('mountebank/src/models/httpsImposter');16const { createHttpsStub } = require('mountebank/src/models/httpsStub');17const { createHttpsRequest } = require('mountebank/src/models/httpsRequest');18const { createHttpsPredicate } = require('mountebank/src/models/httpsPredicate');19const { createHttpsResponse } = require('mountebank/src/models/httpsResponse');20const { createHttpsProxy } = require('mountebank/src/models/httpsProxy');21const { createHttpsProxyResponse } = require('mountebank/src/models/httpsProxyResponse');22const { createSmtpImposter } = require('mountebank/src/models/smtpImposter');23const { createSmtpRequest } = require('mountebank/src/models/smtpRequest');24const { createSmtpPredicate } = require('mountebank/src/models/smtpPredicate');25const { createSmtpStub } = require('mountebank/src/models/smtpStub');26const { createSmtpResponse } = require('mountebank/src/models/smtpResponse');27const { createSmtpProxy } = require('mountebank/src/models/smtpProxy');28const { createSmtpProxyResponse } = require('mountebank/src/models/smtpProxyResponse
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const protocol = 'http';4const host = 'localhost';5const imposters = 1;6const path = '/test';7const method = 'GET';8const response = { test: 'test' };9mb.create({ port, allowInjection: true }, () => {10 mb.post(`/imposters`, { port, protocol, stubs: [{ responses: [{ is: response }] }] }, () => {11 mb.get(`/imposters/${imposters}`, (error, response) => {12 const imposters = JSON.parse(response.body);13 const imposter = imposters[0];14 const stub = imposter.stubs[0];15 const id = stub.id;16 console.log(id);17 mb.del(`/imposters/${imposters}/stubs/${id}`, () => {18 mb.del(`/imposters/${imposters}`, () => {19 mb.stop();20 });21 });22 });23 });24});25const mb = require('mountebank');26const port = 2525;27const protocol = 'http';28const host = 'localhost';29const imposters = 1;30const path = '/test';31const method = 'GET';32const response = { test: 'test' };33mb.create({ port, allowInjection: true }, () => {34 mb.post(`/imposters`, { port, protocol, stubs: [{ responses: [{ is: response }] }] }, () => {35 mb.get(`/imposters/${imposters}`, (error, response) => {36 const imposters = JSON.parse(response.body);37 const imposter = imposters[0];38 const stub = imposter.stubs[0];39 const id = stub.id;40 console.log(id);41 mb.del(`/imposters/${imposters}/stubs?matches=${encodeURIComponent(JSON.stringify({ path, method }))}`, () => {42 mb.del(`/imposters/${imposters}`, () => {43 mb.stop();44 });45 });46 });47 });48});
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3mb.create(port).then(imposter => {4 console.log(`Server is up and running at port ${port}`);5 imposter.post('/user', {6 });7 imposter.get('/user', {8 });9 imposter.put('/user', {10 });11 imposter.delete('/user', {12 });13 imposter.post('/user', {14 });15 imposter.get('/user', {16 });17 imposter.put('/user', {18 });19 imposter.delete('/user', {20 });21 imposter.post('/user', {22 });23 imposter.get('/user', {24 });25 imposter.put('/user', {26 });27 imposter.delete('/user', {28 });29 imposter.post('/user', {30 });31 imposter.get('/user', {32 });33 imposter.put('/user', {
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!!