How to use cache method in Cypress

Best JavaScript code snippet using cypress

cache-base-coverage.js

Source:cache-base-coverage.js Github

copy

Full Screen

1/*2YUI 3.7.3 (build 5687)3Copyright 2012 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7if (typeof _yuitest_coverage == "undefined"){8    _yuitest_coverage = {};9    _yuitest_coverline = function(src, line){10        var coverage = _yuitest_coverage[src];11        if (!coverage.lines[line]){12            coverage.calledLines++;13        }14        coverage.lines[line]++;15    };16    _yuitest_coverfunc = function(src, name, line){17        var coverage = _yuitest_coverage[src],18            funcId = name + ":" + line;19        if (!coverage.functions[funcId]){20            coverage.calledFunctions++;21        }22        coverage.functions[funcId]++;23    };24}25_yuitest_coverage["build/cache-base/cache-base.js"] = {26    lines: {},27    functions: {},28    coveredLines: 0,29    calledLines: 0,30    coveredFunctions: 0,31    calledFunctions: 0,32    path: "build/cache-base/cache-base.js",33    code: []34};35_yuitest_coverage["build/cache-base/cache-base.js"].code=["YUI.add('cache-base', function (Y, NAME) {","","/**"," * The Cache utility provides a common configurable interface for components to"," * cache and retrieve data from a local JavaScript struct."," *"," * @module cache"," * @main"," */","","/**"," * Provides the base class for the YUI Cache utility."," *"," * @submodule cache-base"," */","var LANG = Y.Lang,","    isDate = Y.Lang.isDate,","","/**"," * Base class for the YUI Cache utility."," * @class Cache"," * @extends Base"," * @constructor"," */","Cache = function() {","    Cache.superclass.constructor.apply(this, arguments);","};","","    /////////////////////////////////////////////////////////////////////////////","    //","    // Cache static properties","    //","    /////////////////////////////////////////////////////////////////////////////","Y.mix(Cache, {","    /**","     * Class name.","     *","     * @property NAME","     * @type String","     * @static","     * @final","     * @value \"cache\"","     */","    NAME: \"cache\",","","","    ATTRS: {","        /////////////////////////////////////////////////////////////////////////////","        //","        // Cache Attributes","        //","        /////////////////////////////////////////////////////////////////////////////","","        /**","        * @attribute max","        * @description Maximum number of entries the Cache can hold.","        * Set to 0 to turn off caching.","        * @type Number","        * @default 0","        */","        max: {","            value: 0,","            setter: \"_setMax\"","        },","","        /**","        * @attribute size","        * @description Number of entries currently cached.","        * @type Number","        */","        size: {","            readOnly: true,","            getter: \"_getSize\"","        },","","        /**","        * @attribute uniqueKeys","        * @description Validate uniqueness of stored keys. Default is false and","        * is more performant.","        * @type Boolean","        */","        uniqueKeys: {","            value: false","        },","","        /**","        * @attribute expires","        * @description Absolute Date when data expires or","        * relative number of milliseconds. Zero disables expiration.","        * @type Date | Number","        * @default 0","        */","        expires: {","            value: 0,","            validator: function(v) {","                return Y.Lang.isDate(v) || (Y.Lang.isNumber(v) && v >= 0);","            }","        },","","        /**","         * @attribute entries","         * @description Cached entries.","         * @type Array","         */","        entries: {","            readOnly: true,","            getter: \"_getEntries\"","        }","    }","});","","Y.extend(Cache, Y.Base, {","    /////////////////////////////////////////////////////////////////////////////","    //","    // Cache private properties","    //","    /////////////////////////////////////////////////////////////////////////////","","    /**","     * Array of request/response objects indexed chronologically.","     *","     * @property _entries","     * @type Object[]","     * @private","     */","    _entries: null,","","    /////////////////////////////////////////////////////////////////////////////","    //","    // Cache private methods","    //","    /////////////////////////////////////////////////////////////////////////////","","    /**","    * @method initializer","    * @description Internal init() handler.","    * @param config {Object} Config object.","    * @private","    */","    initializer: function(config) {","","        /**","        * @event add","        * @description Fired when an entry is added.","        * @param e {Event.Facade} Event Facade with the following properties:","         * <dl>","         * <dt>entry (Object)</dt> <dd>The cached entry.</dd>","         * </dl>","        * @preventable _defAddFn","        */","        this.publish(\"add\", {defaultFn: this._defAddFn});","","        /**","        * @event flush","        * @description Fired when the cache is flushed.","        * @param e {Event.Facade} Event Facade object.","        * @preventable _defFlushFn","        */","        this.publish(\"flush\", {defaultFn: this._defFlushFn});","","        /**","        * @event request","        * @description Fired when an entry is requested from the cache.","        * @param e {Event.Facade} Event Facade with the following properties:","        * <dl>","        * <dt>request (Object)</dt> <dd>The request object.</dd>","        * </dl>","        */","","        /**","        * @event retrieve","        * @description Fired when an entry is retrieved from the cache.","        * @param e {Event.Facade} Event Facade with the following properties:","        * <dl>","        * <dt>entry (Object)</dt> <dd>The retrieved entry.</dd>","        * </dl>","        */","","        // Initialize internal values","        this._entries = [];","    },","","    /**","    * @method destructor","    * @description Internal destroy() handler.","    * @private","    */","    destructor: function() {","        this._entries = [];","    },","","    /////////////////////////////////////////////////////////////////////////////","    //","    // Cache protected methods","    //","    /////////////////////////////////////////////////////////////////////////////","","    /**","     * Sets max.","     *","     * @method _setMax","     * @protected","     */","    _setMax: function(value) {","        // If the cache is full, make room by removing stalest element (index=0)","        var entries = this._entries;","        if(value > 0) {","            if(entries) {","                while(entries.length > value) {","                    entries.shift();","                }","            }","        }","        else {","            value = 0;","            this._entries = [];","        }","        return value;","    },","","    /**","     * Gets size.","     *","     * @method _getSize","     * @protected","     */","    _getSize: function() {","        return this._entries.length;","    },","","    /**","     * Gets all entries.","     *","     * @method _getEntries","     * @protected","     */","    _getEntries: function() {","        return this._entries;","    },","","","    /**","     * Adds entry to cache.","     *","     * @method _defAddFn","     * @param e {Event.Facade} Event Facade with the following properties:","     * <dl>","     * <dt>entry (Object)</dt> <dd>The cached entry.</dd>","     * </dl>","     * @protected","     */","    _defAddFn: function(e) {","        var entries = this._entries,","            entry   = e.entry,","            max     = this.get(\"max\"),","            pos;","","        // If uniqueKeys is true and item exists with this key, then remove it.","        if (this.get(\"uniqueKeys\")) {","            pos = this._position(e.entry.request);","            if (LANG.isValue(pos)) {","                entries.splice(pos, 1);","            }","        }","","        // If the cache at or over capacity, make room by removing stalest","        // element(s) starting at index-0.","        while (max && entries.length >= max) {","            entries.shift();","        }","","        // Add entry to cache in the newest position, at the end of the array","        entries[entries.length] = entry;","    },","","    /**","     * Flushes cache.","     *","     * @method _defFlushFn","     * @param e {Event.Facade} Event Facade object.","     * @protected","     */","    _defFlushFn: function(e) {","        var entries = this._entries,","            details = e.details[0],","            pos;","","        //passed an item, flush only that","        if(details && LANG.isValue(details.request)) {","            pos = this._position(details.request);","","            if(LANG.isValue(pos)) {","                entries.splice(pos,1);","","            }","        }","        //no item, flush everything","        else {","            this._entries = [];","        }","    },","","    /**","     * Default overridable method compares current request with given cache entry.","     * Returns true if current request matches the cached request, otherwise","     * false. Implementers should override this method to customize the","     * cache-matching algorithm.","     *","     * @method _isMatch","     * @param request {Object} Request object.","     * @param entry {Object} Cached entry.","     * @return {Boolean} True if current request matches given cached request, false otherwise.","     * @protected","     */","    _isMatch: function(request, entry) {","        if(!entry.expires || new Date() < entry.expires) {","            return (request === entry.request);","        }","        return false;","    },","","    /**","     * Returns position of a request in the entries array, otherwise null.","     *","     * @method _position","     * @param request {Object} Request object.","     * @return {Number} Array position if found, null otherwise.","     * @protected","     */","    _position: function(request) {","        // If cache is enabled...","        var entries = this._entries,","            length = entries.length,","            i = length-1;","","        if((this.get(\"max\") === null) || this.get(\"max\") > 0) {","            // Loop through each cached entry starting from the newest","            for(; i >= 0; i--) {","                // Execute matching function","                if(this._isMatch(request, entries[i])) {","                    return i;","                }","            }","        }","","        return null;","    },","","    /////////////////////////////////////////////////////////////////////////////","    //","    // Cache public methods","    //","    /////////////////////////////////////////////////////////////////////////////","","    /**","     * Adds a new entry to the cache of the format","     * {request:request, response:response, cached:cached, expires:expires}.","     * If cache is full, evicts the stalest entry before adding the new one.","     *","     * @method add","     * @param request {Object} Request value.","     * @param response {Object} Response value.","     */","    add: function(request, response) {","        var expires = this.get(\"expires\");","        if(this.get(\"initialized\") && ((this.get(\"max\") === null) || this.get(\"max\") > 0) &&","                (LANG.isValue(request) || LANG.isNull(request) || LANG.isUndefined(request))) {","            this.fire(\"add\", {entry: {","                request:request,","                response:response,","                cached: new Date(),","                expires: isDate(expires) ? expires :","            (expires ? new Date(new Date().getTime() + this.get(\"expires\")) : null)","            }});","        }","        else {","        }","    },","","    /**","     * Flushes cache.","     *","     * @method flush","     */","    flush: function(request) {","        this.fire(\"flush\", { request: (LANG.isValue(request) ? request : null) });","    },","","    /**","     * Retrieves cached object for given request, if available, and refreshes","     * entry in the cache. Returns null if there is no cache match.","     *","     * @method retrieve","     * @param request {Object} Request object.","     * @return {Object} Cached object with the properties request and response, or null.","     */","    retrieve: function(request) {","        // If cache is enabled...","        var entries = this._entries,","            length = entries.length,","            entry = null,","            pos;","","        if((length > 0) && ((this.get(\"max\") === null) || (this.get(\"max\") > 0))) {","            this.fire(\"request\", {request: request});","","            pos = this._position(request);","","            if(LANG.isValue(pos)) {","                entry = entries[pos];","","                this.fire(\"retrieve\", {entry: entry});","","                // Refresh the position of the cache hit","                if(pos < length-1) {","                    // Remove element from its original location","                    entries.splice(pos,1);","                    // Add as newest","                    entries[entries.length] = entry;","                }","","                return entry;","            }","        }","        return null;","    }","});","","Y.Cache = Cache;","","","}, '3.7.3', {\"requires\": [\"base\"]});"];36_yuitest_coverage["build/cache-base/cache-base.js"].lines = {"1":0,"16":0,"26":0,"34":0,"96":0,"112":0,"151":0,"159":0,"180":0,"189":0,"206":0,"207":0,"208":0,"209":0,"210":0,"215":0,"216":0,"218":0,"228":0,"238":0,"253":0,"259":0,"260":0,"261":0,"262":0,"268":0,"269":0,"273":0,"284":0,"289":0,"290":0,"292":0,"293":0,"299":0,"316":0,"317":0,"319":0,"332":0,"336":0,"338":0,"340":0,"341":0,"346":0,"365":0,"366":0,"368":0,"386":0,"399":0,"404":0,"405":0,"407":0,"409":0,"410":0,"412":0,"415":0,"417":0,"419":0,"422":0,"425":0,"429":0};37_yuitest_coverage["build/cache-base/cache-base.js"].functions = {"Cache:25":0,"validator:95":0,"initializer:140":0,"destructor:188":0,"_setMax:204":0,"_getSize:227":0,"_getEntries:237":0,"_defAddFn:252":0,"_defFlushFn:283":0,"_isMatch:315":0,"_position:330":0,"add:364":0,"flush:385":0,"retrieve:397":0,"(anonymous 1):1":0};38_yuitest_coverage["build/cache-base/cache-base.js"].coveredLines = 60;39_yuitest_coverage["build/cache-base/cache-base.js"].coveredFunctions = 15;40_yuitest_coverline("build/cache-base/cache-base.js", 1);41YUI.add('cache-base', function (Y, NAME) {42/**43 * The Cache utility provides a common configurable interface for components to44 * cache and retrieve data from a local JavaScript struct.45 *46 * @module cache47 * @main48 */49/**50 * Provides the base class for the YUI Cache utility.51 *52 * @submodule cache-base53 */54_yuitest_coverfunc("build/cache-base/cache-base.js", "(anonymous 1)", 1);55_yuitest_coverline("build/cache-base/cache-base.js", 16);56var LANG = Y.Lang,57    isDate = Y.Lang.isDate,58/**59 * Base class for the YUI Cache utility.60 * @class Cache61 * @extends Base62 * @constructor63 */64Cache = function() {65    _yuitest_coverfunc("build/cache-base/cache-base.js", "Cache", 25);66_yuitest_coverline("build/cache-base/cache-base.js", 26);67Cache.superclass.constructor.apply(this, arguments);68};69    /////////////////////////////////////////////////////////////////////////////70    //71    // Cache static properties72    //73    /////////////////////////////////////////////////////////////////////////////74_yuitest_coverline("build/cache-base/cache-base.js", 34);75Y.mix(Cache, {76    /**77     * Class name.78     *79     * @property NAME80     * @type String81     * @static82     * @final83     * @value "cache"84     */85    NAME: "cache",86    ATTRS: {87        /////////////////////////////////////////////////////////////////////////////88        //89        // Cache Attributes90        //91        /////////////////////////////////////////////////////////////////////////////92        /**93        * @attribute max94        * @description Maximum number of entries the Cache can hold.95        * Set to 0 to turn off caching.96        * @type Number97        * @default 098        */99        max: {100            value: 0,101            setter: "_setMax"102        },103        /**104        * @attribute size105        * @description Number of entries currently cached.106        * @type Number107        */108        size: {109            readOnly: true,110            getter: "_getSize"111        },112        /**113        * @attribute uniqueKeys114        * @description Validate uniqueness of stored keys. Default is false and115        * is more performant.116        * @type Boolean117        */118        uniqueKeys: {119            value: false120        },121        /**122        * @attribute expires123        * @description Absolute Date when data expires or124        * relative number of milliseconds. Zero disables expiration.125        * @type Date | Number126        * @default 0127        */128        expires: {129            value: 0,130            validator: function(v) {131                _yuitest_coverfunc("build/cache-base/cache-base.js", "validator", 95);132_yuitest_coverline("build/cache-base/cache-base.js", 96);133return Y.Lang.isDate(v) || (Y.Lang.isNumber(v) && v >= 0);134            }135        },136        /**137         * @attribute entries138         * @description Cached entries.139         * @type Array140         */141        entries: {142            readOnly: true,143            getter: "_getEntries"144        }145    }146});147_yuitest_coverline("build/cache-base/cache-base.js", 112);148Y.extend(Cache, Y.Base, {149    /////////////////////////////////////////////////////////////////////////////150    //151    // Cache private properties152    //153    /////////////////////////////////////////////////////////////////////////////154    /**155     * Array of request/response objects indexed chronologically.156     *157     * @property _entries158     * @type Object[]159     * @private160     */161    _entries: null,162    /////////////////////////////////////////////////////////////////////////////163    //164    // Cache private methods165    //166    /////////////////////////////////////////////////////////////////////////////167    /**168    * @method initializer169    * @description Internal init() handler.170    * @param config {Object} Config object.171    * @private172    */173    initializer: function(config) {174        /**175        * @event add176        * @description Fired when an entry is added.177        * @param e {Event.Facade} Event Facade with the following properties:178         * <dl>179         * <dt>entry (Object)</dt> <dd>The cached entry.</dd>180         * </dl>181        * @preventable _defAddFn182        */183        _yuitest_coverfunc("build/cache-base/cache-base.js", "initializer", 140);184_yuitest_coverline("build/cache-base/cache-base.js", 151);185this.publish("add", {defaultFn: this._defAddFn});186        /**187        * @event flush188        * @description Fired when the cache is flushed.189        * @param e {Event.Facade} Event Facade object.190        * @preventable _defFlushFn191        */192        _yuitest_coverline("build/cache-base/cache-base.js", 159);193this.publish("flush", {defaultFn: this._defFlushFn});194        /**195        * @event request196        * @description Fired when an entry is requested from the cache.197        * @param e {Event.Facade} Event Facade with the following properties:198        * <dl>199        * <dt>request (Object)</dt> <dd>The request object.</dd>200        * </dl>201        */202        /**203        * @event retrieve204        * @description Fired when an entry is retrieved from the cache.205        * @param e {Event.Facade} Event Facade with the following properties:206        * <dl>207        * <dt>entry (Object)</dt> <dd>The retrieved entry.</dd>208        * </dl>209        */210        // Initialize internal values211        _yuitest_coverline("build/cache-base/cache-base.js", 180);212this._entries = [];213    },214    /**215    * @method destructor216    * @description Internal destroy() handler.217    * @private218    */219    destructor: function() {220        _yuitest_coverfunc("build/cache-base/cache-base.js", "destructor", 188);221_yuitest_coverline("build/cache-base/cache-base.js", 189);222this._entries = [];223    },224    /////////////////////////////////////////////////////////////////////////////225    //226    // Cache protected methods227    //228    /////////////////////////////////////////////////////////////////////////////229    /**230     * Sets max.231     *232     * @method _setMax233     * @protected234     */235    _setMax: function(value) {236        // If the cache is full, make room by removing stalest element (index=0)237        _yuitest_coverfunc("build/cache-base/cache-base.js", "_setMax", 204);238_yuitest_coverline("build/cache-base/cache-base.js", 206);239var entries = this._entries;240        _yuitest_coverline("build/cache-base/cache-base.js", 207);241if(value > 0) {242            _yuitest_coverline("build/cache-base/cache-base.js", 208);243if(entries) {244                _yuitest_coverline("build/cache-base/cache-base.js", 209);245while(entries.length > value) {246                    _yuitest_coverline("build/cache-base/cache-base.js", 210);247entries.shift();248                }249            }250        }251        else {252            _yuitest_coverline("build/cache-base/cache-base.js", 215);253value = 0;254            _yuitest_coverline("build/cache-base/cache-base.js", 216);255this._entries = [];256        }257        _yuitest_coverline("build/cache-base/cache-base.js", 218);258return value;259    },260    /**261     * Gets size.262     *263     * @method _getSize264     * @protected265     */266    _getSize: function() {267        _yuitest_coverfunc("build/cache-base/cache-base.js", "_getSize", 227);268_yuitest_coverline("build/cache-base/cache-base.js", 228);269return this._entries.length;270    },271    /**272     * Gets all entries.273     *274     * @method _getEntries275     * @protected276     */277    _getEntries: function() {278        _yuitest_coverfunc("build/cache-base/cache-base.js", "_getEntries", 237);279_yuitest_coverline("build/cache-base/cache-base.js", 238);280return this._entries;281    },282    /**283     * Adds entry to cache.284     *285     * @method _defAddFn286     * @param e {Event.Facade} Event Facade with the following properties:287     * <dl>288     * <dt>entry (Object)</dt> <dd>The cached entry.</dd>289     * </dl>290     * @protected291     */292    _defAddFn: function(e) {293        _yuitest_coverfunc("build/cache-base/cache-base.js", "_defAddFn", 252);294_yuitest_coverline("build/cache-base/cache-base.js", 253);295var entries = this._entries,296            entry   = e.entry,297            max     = this.get("max"),298            pos;299        // If uniqueKeys is true and item exists with this key, then remove it.300        _yuitest_coverline("build/cache-base/cache-base.js", 259);301if (this.get("uniqueKeys")) {302            _yuitest_coverline("build/cache-base/cache-base.js", 260);303pos = this._position(e.entry.request);304            _yuitest_coverline("build/cache-base/cache-base.js", 261);305if (LANG.isValue(pos)) {306                _yuitest_coverline("build/cache-base/cache-base.js", 262);307entries.splice(pos, 1);308            }309        }310        // If the cache at or over capacity, make room by removing stalest311        // element(s) starting at index-0.312        _yuitest_coverline("build/cache-base/cache-base.js", 268);313while (max && entries.length >= max) {314            _yuitest_coverline("build/cache-base/cache-base.js", 269);315entries.shift();316        }317        // Add entry to cache in the newest position, at the end of the array318        _yuitest_coverline("build/cache-base/cache-base.js", 273);319entries[entries.length] = entry;320    },321    /**322     * Flushes cache.323     *324     * @method _defFlushFn325     * @param e {Event.Facade} Event Facade object.326     * @protected327     */328    _defFlushFn: function(e) {329        _yuitest_coverfunc("build/cache-base/cache-base.js", "_defFlushFn", 283);330_yuitest_coverline("build/cache-base/cache-base.js", 284);331var entries = this._entries,332            details = e.details[0],333            pos;334        //passed an item, flush only that335        _yuitest_coverline("build/cache-base/cache-base.js", 289);336if(details && LANG.isValue(details.request)) {337            _yuitest_coverline("build/cache-base/cache-base.js", 290);338pos = this._position(details.request);339            _yuitest_coverline("build/cache-base/cache-base.js", 292);340if(LANG.isValue(pos)) {341                _yuitest_coverline("build/cache-base/cache-base.js", 293);342entries.splice(pos,1);343            }344        }345        //no item, flush everything346        else {347            _yuitest_coverline("build/cache-base/cache-base.js", 299);348this._entries = [];349        }350    },351    /**352     * Default overridable method compares current request with given cache entry.353     * Returns true if current request matches the cached request, otherwise354     * false. Implementers should override this method to customize the355     * cache-matching algorithm.356     *357     * @method _isMatch358     * @param request {Object} Request object.359     * @param entry {Object} Cached entry.360     * @return {Boolean} True if current request matches given cached request, false otherwise.361     * @protected362     */363    _isMatch: function(request, entry) {364        _yuitest_coverfunc("build/cache-base/cache-base.js", "_isMatch", 315);365_yuitest_coverline("build/cache-base/cache-base.js", 316);366if(!entry.expires || new Date() < entry.expires) {367            _yuitest_coverline("build/cache-base/cache-base.js", 317);368return (request === entry.request);369        }370        _yuitest_coverline("build/cache-base/cache-base.js", 319);371return false;372    },373    /**374     * Returns position of a request in the entries array, otherwise null.375     *376     * @method _position377     * @param request {Object} Request object.378     * @return {Number} Array position if found, null otherwise.379     * @protected380     */381    _position: function(request) {382        // If cache is enabled...383        _yuitest_coverfunc("build/cache-base/cache-base.js", "_position", 330);384_yuitest_coverline("build/cache-base/cache-base.js", 332);385var entries = this._entries,386            length = entries.length,387            i = length-1;388        _yuitest_coverline("build/cache-base/cache-base.js", 336);389if((this.get("max") === null) || this.get("max") > 0) {390            // Loop through each cached entry starting from the newest391            _yuitest_coverline("build/cache-base/cache-base.js", 338);392for(; i >= 0; i--) {393                // Execute matching function394                _yuitest_coverline("build/cache-base/cache-base.js", 340);395if(this._isMatch(request, entries[i])) {396                    _yuitest_coverline("build/cache-base/cache-base.js", 341);397return i;398                }399            }400        }401        _yuitest_coverline("build/cache-base/cache-base.js", 346);402return null;403    },404    /////////////////////////////////////////////////////////////////////////////405    //406    // Cache public methods407    //408    /////////////////////////////////////////////////////////////////////////////409    /**410     * Adds a new entry to the cache of the format411     * {request:request, response:response, cached:cached, expires:expires}.412     * If cache is full, evicts the stalest entry before adding the new one.413     *414     * @method add415     * @param request {Object} Request value.416     * @param response {Object} Response value.417     */418    add: function(request, response) {419        _yuitest_coverfunc("build/cache-base/cache-base.js", "add", 364);420_yuitest_coverline("build/cache-base/cache-base.js", 365);421var expires = this.get("expires");422        _yuitest_coverline("build/cache-base/cache-base.js", 366);423if(this.get("initialized") && ((this.get("max") === null) || this.get("max") > 0) &&424                (LANG.isValue(request) || LANG.isNull(request) || LANG.isUndefined(request))) {425            _yuitest_coverline("build/cache-base/cache-base.js", 368);426this.fire("add", {entry: {427                request:request,428                response:response,429                cached: new Date(),430                expires: isDate(expires) ? expires :431            (expires ? new Date(new Date().getTime() + this.get("expires")) : null)432            }});433        }434        else {435        }436    },437    /**438     * Flushes cache.439     *440     * @method flush441     */442    flush: function(request) {443        _yuitest_coverfunc("build/cache-base/cache-base.js", "flush", 385);444_yuitest_coverline("build/cache-base/cache-base.js", 386);445this.fire("flush", { request: (LANG.isValue(request) ? request : null) });446    },447    /**448     * Retrieves cached object for given request, if available, and refreshes449     * entry in the cache. Returns null if there is no cache match.450     *451     * @method retrieve452     * @param request {Object} Request object.453     * @return {Object} Cached object with the properties request and response, or null.454     */455    retrieve: function(request) {456        // If cache is enabled...457        _yuitest_coverfunc("build/cache-base/cache-base.js", "retrieve", 397);458_yuitest_coverline("build/cache-base/cache-base.js", 399);459var entries = this._entries,460            length = entries.length,461            entry = null,462            pos;463        _yuitest_coverline("build/cache-base/cache-base.js", 404);464if((length > 0) && ((this.get("max") === null) || (this.get("max") > 0))) {465            _yuitest_coverline("build/cache-base/cache-base.js", 405);466this.fire("request", {request: request});467            _yuitest_coverline("build/cache-base/cache-base.js", 407);468pos = this._position(request);469            _yuitest_coverline("build/cache-base/cache-base.js", 409);470if(LANG.isValue(pos)) {471                _yuitest_coverline("build/cache-base/cache-base.js", 410);472entry = entries[pos];473                _yuitest_coverline("build/cache-base/cache-base.js", 412);474this.fire("retrieve", {entry: entry});475                // Refresh the position of the cache hit476                _yuitest_coverline("build/cache-base/cache-base.js", 415);477if(pos < length-1) {478                    // Remove element from its original location479                    _yuitest_coverline("build/cache-base/cache-base.js", 417);480entries.splice(pos,1);481                    // Add as newest482                    _yuitest_coverline("build/cache-base/cache-base.js", 419);483entries[entries.length] = entry;484                }485                _yuitest_coverline("build/cache-base/cache-base.js", 422);486return entry;487            }488        }489        _yuitest_coverline("build/cache-base/cache-base.js", 425);490return null;491    }492});493_yuitest_coverline("build/cache-base/cache-base.js", 429);494Y.Cache = Cache;...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

1/* global describe, it, before, beforeEach, afterEach */2'use strict';3var chai = require('chai'),4    expect = chai.expect,5    sinon = require('sinon'),6    sinonChai = require('sinon-chai'),7    Cache = require('./index').Cache,8    cache = new Cache(),9    clock;10chai.use(sinonChai);11describe('node-cache', function() {12  beforeEach(function() {13    clock = sinon.useFakeTimers();14    cache.clear();15  });16  afterEach(function() {17    clock.restore();18  });19  describe('put()', function() {20    before(function() {21      cache.debug(false);22    });23    it('should allow adding a new item to the cache', function() {24      expect(function() {25        cache.put('key', 'value');26      }).to.not.throw();27    });28    it('should allow adding a new item to the cache with a timeout', function() {29      expect(function() {30        cache.put('key', 'value', 100);31      }).to.not.throw();32    });33    it('should allow adding a new item to the cache with a timeout callback', function() {34      expect(function() {35        cache.put('key', 'value', 100, function() {});36      }).to.not.throw();37    });38    it('should throw an error given a non-numeric timeout', function() {39      expect(function() {40        cache.put('key', 'value', 'foo');41      }).to.throw();42    });43    it('should throw an error given a timeout of NaN', function() {44      expect(function() {45        cache.put('key', 'value', NaN);46      }).to.throw();47    });48    it('should throw an error given a timeout of 0', function() {49      expect(function() {50        cache.put('key', 'value', 0);51      }).to.throw();52    });53    it('should throw an error given a negative timeout', function() {54      expect(function() {55        cache.put('key', 'value', -100);56      }).to.throw();57    });58    it('should throw an error given a non-function timeout callback', function() {59      expect(function() {60        cache.put('key', 'value', 100, 'foo');61      }).to.throw();62    });63    it('should cause the timeout callback to fire once the cache item expires', function() {64      var spy = sinon.spy();65      cache.put('key', 'value', 1000, spy);66      clock.tick(999);67      expect(spy).to.not.have.been.called;68      clock.tick(1);69      expect(spy).to.have.been.calledOnce.and.calledWith('key', 'value');70    });71    it('should override the timeout callback on a new put() with a different timeout callback', function() {72      var spy1 = sinon.spy();73      var spy2 = sinon.spy();74      cache.put('key', 'value', 1000, spy1);75      clock.tick(999);76      cache.put('key', 'value', 1000, spy2)77      clock.tick(1001);78      expect(spy1).to.not.have.been.called;79      expect(spy2).to.have.been.calledOnce.and.calledWith('key', 'value');80    });81    it('should cancel the timeout callback on a new put() without a timeout callback', function() {82      var spy = sinon.spy();83      cache.put('key', 'value', 1000, spy);84      clock.tick(999);85      cache.put('key', 'value');86      clock.tick(1);87      expect(spy).to.not.have.been.called;88    });89    it('should return the cached value', function() {90      expect(cache.put('key', 'value')).to.equal('value');91    });92  });93  describe('del()', function() {94    before(function() {95      cache.debug(false);96    });97    it('should return false given a key for an empty cache', function() {98      expect(cache.del('miss')).to.be.false;99    });100    it('should return false given a key not in a non-empty cache', function() {101      cache.put('key', 'value');102      expect(cache.del('miss')).to.be.false;103    });104    it('should return true given a key in the cache', function() {105      cache.put('key', 'value');106      expect(cache.del('key')).to.be.true;107    });108    it('should remove the provided key from the cache', function() {109      cache.put('key', 'value');110      expect(cache.get('key')).to.equal('value');111      expect(cache.del('key')).to.be.true;112      expect(cache.get('key')).to.be.null;113    });114    it('should decrement the cache size by 1', function() {115      cache.put('key', 'value');116      expect(cache.size()).to.equal(1);117      expect(cache.del('key')).to.be.true;118      expect(cache.size()).to.equal(0);119    });120    it('should not remove other keys in the cache', function() {121      cache.put('key1', 'value1');122      cache.put('key2', 'value2');123      cache.put('key3', 'value3');124      expect(cache.get('key1')).to.equal('value1');125      expect(cache.get('key2')).to.equal('value2');126      expect(cache.get('key3')).to.equal('value3');127      cache.del('key1');128      expect(cache.get('key1')).to.be.null;129      expect(cache.get('key2')).to.equal('value2');130      expect(cache.get('key3')).to.equal('value3');131    });132    it('should only delete a key from the cache once even if called multiple times in a row', function() {133      cache.put('key1', 'value1');134      cache.put('key2', 'value2');135      cache.put('key3', 'value3');136      expect(cache.size()).to.equal(3);137      cache.del('key1');138      cache.del('key1');139      cache.del('key1');140      expect(cache.size()).to.equal(2);141    });142    it('should handle deleting keys which were previously deleted and then re-added to the cache', function() {143      cache.put('key', 'value');144      expect(cache.get('key')).to.equal('value');145      cache.del('key');146      expect(cache.get('key')).to.be.null;147      cache.put('key', 'value');148      expect(cache.get('key')).to.equal('value');149      cache.del('key');150      expect(cache.get('key')).to.be.null;151    });152    it('should return true given an non-expired key', function() {153      cache.put('key', 'value', 1000);154      clock.tick(999);155      expect(cache.del('key')).to.be.true;156    });157    it('should return false given an expired key', function() {158      cache.put('key', 'value', 1000);159      clock.tick(1000);160      expect(cache.del('key')).to.be.false;161    });162    it('should cancel the timeout callback for the deleted key', function() {163      var spy = sinon.spy();164      cache.put('key', 'value', 1000, spy);165      cache.del('key');166      clock.tick(1000);167      expect(spy).to.not.have.been.called;168    });169    it('should handle deletion of many items', function(done) {170      clock.restore();171      var num = 1000;172      for(var i = 0; i < num; i++){173        cache.put('key' + i, i, 1000);174      }175      expect(cache.size()).to.equal(num);176      setTimeout(function(){177        expect(cache.size()).to.equal(0);178        done();179      }, 1000);180    });181  });182  describe('clear()', function() {183    before(function() {184      cache.debug(false);185    });186    it('should have no effect given an empty cache', function() {187      expect(cache.size()).to.equal(0);188      cache.clear();189      expect(cache.size()).to.equal(0);190    });191    it('should remove all existing keys in the cache', function() {192      cache.put('key1', 'value1');193      cache.put('key2', 'value2');194      cache.put('key3', 'value3');195      expect(cache.size()).to.equal(3);196      cache.clear();197      expect(cache.size()).to.equal(0);198    });199    it('should remove the keys in the cache', function() {200      cache.put('key1', 'value1');201      cache.put('key2', 'value2');202      cache.put('key3', 'value3');203      expect(cache.get('key1')).to.equal('value1');204      expect(cache.get('key2')).to.equal('value2');205      expect(cache.get('key3')).to.equal('value3');206      cache.clear();207      expect(cache.get('key1')).to.be.null;208      expect(cache.get('key2')).to.be.null;209      expect(cache.get('key3')).to.be.null;210    });211    it('should reset the cache size to 0', function() {212      cache.put('key1', 'value1');213      cache.put('key2', 'value2');214      cache.put('key3', 'value3');215      expect(cache.size()).to.equal(3);216      cache.clear();217      expect(cache.size()).to.equal(0);218    });219    it('should reset the debug cache hits', function() {220      cache.debug(true);221      cache.put('key', 'value');222      cache.get('key');223      expect(cache.hits()).to.equal(1);224      cache.clear();225      expect(cache.hits()).to.equal(0);226    });227    it('should reset the debug cache misses', function() {228      cache.debug(true);229      cache.put('key', 'value');230      cache.get('miss1');231      expect(cache.misses()).to.equal(1);232      cache.clear();233      expect(cache.misses()).to.equal(0);234    });235    it('should cancel the timeout callbacks for all existing keys', function() {236      var spy1 = sinon.spy();237      var spy2 = sinon.spy();238      var spy3 = sinon.spy();239      cache.put('key1', 'value1', 1000, spy1);240      cache.put('key2', 'value2', 1000, spy2);241      cache.put('key3', 'value3', 1000, spy3);242      cache.clear();243      clock.tick(1000);244      expect(spy1).to.not.have.been.called;245      expect(spy2).to.not.have.been.called;246      expect(spy3).to.not.have.been.called;247    });248  });249  describe('get()', function() {250    before(function() {251      cache.debug(false);252    });253    it('should return null given a key for an empty cache', function() {254      expect(cache.get('miss')).to.be.null;255    });256    it('should return null given a key not in a non-empty cache', function() {257      cache.put('key', 'value');258      expect(cache.get('miss')).to.be.null;259    });260    it('should return the corresponding value of a key in the cache', function() {261      cache.put('key', 'value');262      expect(cache.get('key')).to.equal('value');263    });264    it('should return the latest corresponding value of a key in the cache', function() {265      cache.put('key', 'value1');266      cache.put('key', 'value2');267      cache.put('key', 'value3');268      expect(cache.get('key')).to.equal('value3');269    });270    it('should handle various types of cache keys', function() {271      var keys = [null, undefined, NaN, true, false, 0, 1, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, '', 'a', [], {}, [1, 'a', false], {a:1,b:'a',c:false}, function() {}];272      keys.forEach(function(key, index) {273        var value = 'value' + index;274        cache.put(key, value);275        expect(cache.get(key)).to.deep.equal(value);276      });277    });278    it('should handle various types of cache values', function() {279      var values = [null, undefined, NaN, true, false, 0, 1, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, '', 'a', [], {}, [1, 'a', false], {a:1,b:'a',c:false}, function() {}];280      values.forEach(function(value, index) {281        var key = 'key' + index;282        cache.put(key, value);283        expect(cache.get(key)).to.deep.equal(value);284      });285    });286    it('should not set a timeout given no expiration time', function() {287      cache.put('key', 'value');288      clock.tick(1000);289      expect(cache.get('key')).to.equal('value');290    });291    it('should return the corresponding value of a non-expired key in the cache', function() {292      cache.put('key', 'value', 1000);293      clock.tick(999);294      expect(cache.get('key')).to.equal('value');295    });296    it('should return null given an expired key', function() {297      cache.put('key', 'value', 1000);298      clock.tick(1000);299      expect(cache.get('key')).to.be.null;300    });301    it('should return null given an expired key', function() {302      cache.put('key', 'value', 1000);303      clock.tick(1000);304      expect(cache.get('key')).to.be.null;305    });306    it('should return null given a key which is a property on the Object prototype', function() {307      expect(cache.get('toString')).to.be.null;308    });309    it('should allow reading the value for a key which is a property on the Object prototype', function() {310      cache.put('toString', 'value');311      expect(cache.get('toString')).to.equal('value');312    });313  });314  describe('size()', function() {315    before(function() {316      cache.debug(false);317    });318    it('should return 0 given a fresh cache', function() {319      expect(cache.size()).to.equal(0);320    });321    it('should return 1 after adding a single item to the cache', function() {322      cache.put('key', 'value');323      expect(cache.size()).to.equal(1);324    });325    it('should return 3 after adding three items to the cache', function() {326      cache.put('key1', 'value1');327      cache.put('key2', 'value2');328      cache.put('key3', 'value3');329      expect(cache.size()).to.equal(3);330    });331    it('should not multi-count duplicate items added to the cache', function() {332      cache.put('key', 'value1');333      expect(cache.size()).to.equal(1);334      cache.put('key', 'value2');335      expect(cache.size()).to.equal(1);336    });337    it('should update when a key in the cache expires', function() {338      cache.put('key', 'value', 1000);339      expect(cache.size()).to.equal(1);340      clock.tick(999);341      expect(cache.size()).to.equal(1);342      clock.tick(1);343      expect(cache.size()).to.equal(0);344    });345  });346  describe('memsize()', function() {347    before(function() {348      cache.debug(false);349    });350    it('should return 0 given a fresh cache', function() {351      expect(cache.memsize()).to.equal(0);352    });353    it('should return 1 after adding a single item to the cache', function() {354      cache.put('key', 'value');355      expect(cache.memsize()).to.equal(1);356    });357    it('should return 3 after adding three items to the cache', function() {358      cache.put('key1', 'value1');359      cache.put('key2', 'value2');360      cache.put('key3', 'value3');361      expect(cache.memsize()).to.equal(3);362    });363    it('should not multi-count duplicate items added to the cache', function() {364      cache.put('key', 'value1');365      expect(cache.memsize()).to.equal(1);366      cache.put('key', 'value2');367      expect(cache.memsize()).to.equal(1);368    });369    it('should update when a key in the cache expires', function() {370      cache.put('key', 'value', 1000);371      expect(cache.memsize()).to.equal(1);372      clock.tick(999);373      expect(cache.memsize()).to.equal(1);374      clock.tick(1);375      expect(cache.memsize()).to.equal(0);376    });377  });378  describe('debug()', function() {379    it('should not count cache hits when false', function() {380      cache.debug(false);381      cache.put('key', 'value');382      cache.get('key');383      expect(cache.hits()).to.equal(0);384    });385    it('should not count cache misses when false', function() {386      cache.debug(false);387      cache.put('key', 'value');388      cache.get('miss1');389      expect(cache.misses()).to.equal(0);390    });391    it('should count cache hits when true', function() {392      cache.debug(true);393      cache.put('key', 'value');394      cache.get('key');395      expect(cache.hits()).to.equal(1);396    });397    it('should count cache misses when true', function() {398      cache.debug(true);399      cache.put('key', 'value');400      cache.get('miss1');401      expect(cache.misses()).to.equal(1);402    });403  });404  describe('hits()', function() {405    before(function() {406      cache.debug(true);407    });408    it('should return 0 given an empty cache', function() {409      expect(cache.hits()).to.equal(0);410    });411    it('should return 0 given a non-empty cache which has not been accessed', function() {412      cache.put('key', 'value');413      expect(cache.hits()).to.equal(0);414    });415    it('should return 0 given a non-empty cache which has had only misses', function() {416      cache.put('key', 'value');417      cache.get('miss1');418      cache.get('miss2');419      cache.get('miss3');420      expect(cache.hits()).to.equal(0);421    });422    it('should return 1 given a non-empty cache which has had a single hit', function() {423      cache.put('key', 'value');424      cache.get('key');425      expect(cache.hits()).to.equal(1);426    });427    it('should return 3 given a non-empty cache which has had three hits on the same key', function() {428      cache.put('key', 'value');429      cache.get('key');430      cache.get('key');431      cache.get('key');432      expect(cache.hits()).to.equal(3);433    });434    it('should return 3 given a non-empty cache which has had three hits across many keys', function() {435      cache.put('key1', 'value1');436      cache.put('key2', 'value2');437      cache.put('key3', 'value3');438      cache.get('key1');439      cache.get('key2');440      cache.get('key3');441      expect(cache.hits()).to.equal(3);442    });443    it('should return the correct value after a sequence of hits and misses', function() {444      cache.put('key1', 'value1');445      cache.put('key2', 'value2');446      cache.put('key3', 'value3');447      cache.get('key1');448      cache.get('miss');449      cache.get('key3');450      expect(cache.hits()).to.equal(2);451    });452    it('should not count hits for expired keys', function() {453      cache.put('key', 'value', 1000);454      cache.get('key');455      expect(cache.hits()).to.equal(1);456      clock.tick(999);457      cache.get('key');458      expect(cache.hits()).to.equal(2);459      clock.tick(1);460      cache.get('key');461      expect(cache.hits()).to.equal(2);462    });463  });464  describe('misses()', function() {465    before(function() {466      cache.debug(true);467    });468    it('should return 0 given an empty cache', function() {469      expect(cache.misses()).to.equal(0);470    });471    it('should return 0 given a non-empty cache which has not been accessed', function() {472      cache.put('key', 'value');473      expect(cache.misses()).to.equal(0);474    });475    it('should return 0 given a non-empty cache which has had only hits', function() {476      cache.put('key', 'value');477      cache.get('key');478      cache.get('key');479      cache.get('key');480      expect(cache.misses()).to.equal(0);481    });482    it('should return 1 given a non-empty cache which has had a single miss', function() {483      cache.put('key', 'value');484      cache.get('miss');485      expect(cache.misses()).to.equal(1);486    });487    it('should return 3 given a non-empty cache which has had three misses', function() {488      cache.put('key', 'value');489      cache.get('miss1');490      cache.get('miss2');491      cache.get('miss3');492      expect(cache.misses()).to.equal(3);493    });494    it('should return the correct value after a sequence of hits and misses', function() {495      cache.put('key1', 'value1');496      cache.put('key2', 'value2');497      cache.put('key3', 'value3');498      cache.get('key1');499      cache.get('miss');500      cache.get('key3');501      expect(cache.misses()).to.equal(1);502    });503    it('should count misses for expired keys', function() {504      cache.put('key', 'value', 1000);505      cache.get('key');506      expect(cache.misses()).to.equal(0);507      clock.tick(999);508      cache.get('key');509      expect(cache.misses()).to.equal(0);510      clock.tick(1);511      cache.get('key');512      expect(cache.misses()).to.equal(1);513    });514  });515  describe('keys()', function() {516    before(function() {517      cache.debug(false);518    });519    it('should return an empty array given an empty cache', function() {520      expect(cache.keys()).to.deep.equal([]);521    });522    it('should return a single key after adding a single item to the cache', function() {523      cache.put('key', 'value');524      expect(cache.keys()).to.deep.equal(['key']);525    });526    it('should return 3 keys after adding three items to the cache', function() {527      cache.put('key1', 'value1');528      cache.put('key2', 'value2');529      cache.put('key3', 'value3');530      expect(cache.keys()).to.deep.equal(['key1', 'key2', 'key3']);531    });532    it('should not multi-count duplicate items added to the cache', function() {533      cache.put('key', 'value1');534      expect(cache.keys()).to.deep.equal(['key']);535      cache.put('key', 'value2');536      expect(cache.keys()).to.deep.equal(['key']);537    });538    it('should update when a key in the cache expires', function() {539      cache.put('key', 'value', 1000);540      expect(cache.keys()).to.deep.equal(['key']);541      clock.tick(999);542      expect(cache.keys()).to.deep.equal(['key']);543      clock.tick(1);544      expect(cache.keys()).to.deep.equal([]);545    });546  });547  describe('export()', function() {548    var START_TIME = 10000;549    var BASIC_EXPORT = JSON.stringify({550      key: {551        value: 'value',552        expire: START_TIME + 1000,553      },554    });555    before(function() {556      cache.debug(false);557    });558    beforeEach(function() {559      clock.tick(START_TIME);560    });561    it('should return an empty object given an empty cache', function() {562      expect(cache.exportJson()).to.equal(JSON.stringify({}));563    });564    it('should return a single record after adding a single item to the cache', function() {565      cache.put('key', 'value', 1000);566      expect(cache.exportJson()).to.equal(BASIC_EXPORT);567    });568    it('should return multiple records with expiry', function() {569      cache.put('key1', 'value1');570      cache.put('key2', 'value2', 1000);571      expect(cache.exportJson()).to.equal(JSON.stringify({572        key1: {573          value: 'value1',574          expire: 'NaN',575        },576        key2: {577          value: 'value2',578          expire: START_TIME + 1000,579        },580      }));581    });582    it('should update when a key in the cache expires', function() {583      cache.put('key', 'value', 1000);584      expect(cache.exportJson()).to.equal(BASIC_EXPORT);585      clock.tick(999);586      expect(cache.exportJson()).to.equal(BASIC_EXPORT);587      clock.tick(1);588      expect(cache.exportJson()).to.equal(JSON.stringify({}));589    });590  });591  describe('import()', function() {592    var START_TIME = 10000;593    var BASIC_EXPORT = JSON.stringify({594      key: {595        value: 'value',596        expire: START_TIME + 1000,597      },598    });599    before(function() {600      cache.debug(false);601    });602    beforeEach(function() {603      clock.tick(START_TIME);604    });605    it('should import an empty object into an empty cache', function() {606      var exportedJson = cache.exportJson();607      cache.clear();608      cache.importJson(exportedJson);609      expect(cache.exportJson()).to.equal(JSON.stringify({}));610    });611    it('should import records into an empty cache', function() {612      cache.put('key1', 'value1');613      cache.put('key2', 'value2', 1000);614      var exportedJson = cache.exportJson();615      cache.clear();616      cache.importJson(exportedJson);617      expect(cache.exportJson()).to.equal(JSON.stringify({618        key1: {619          value: 'value1',620          expire: 'NaN',621        },622        key2: {623          value: 'value2',624          expire: START_TIME + 1000,625        },626      }));627    });628    it('should import records into an already-existing cache', function() {629      cache.put('key1', 'value1');630      cache.put('key2', 'value2', 1000);631      var exportedJson = cache.exportJson();632      cache.put('key1', 'changed value', 5000);633      cache.put('key3', 'value3', 500);634      cache.importJson(exportedJson);635      expect(cache.exportJson()).to.equal(JSON.stringify({636        key1: {637          value: 'value1',638          expire: 'NaN',639        },640        key2: {641          value: 'value2',642          expire: START_TIME + 1000,643        },644        key3: {645          value: 'value3',646          expire: START_TIME + 500,647        },648      }));649    });650    it('should import records into an already-existing cache and skip duplicates', function() {651      cache.debug(true);652      cache.put('key1', 'value1');653      cache.put('key2', 'value2', 1000);654      var exportedJson = cache.exportJson();655      cache.clear();656      cache.put('key1', 'changed value', 5000);657      cache.put('key3', 'value3', 500);658      cache.importJson(exportedJson, { skipDuplicates: true });659      expect(cache.exportJson()).to.equal(JSON.stringify({660        key1: {661          value: 'changed value',662          expire: START_TIME + 5000,663        },664        key3: {665          value: 'value3',666          expire: START_TIME + 500,667        },668        key2: {669          value: 'value2',670          expire: START_TIME + 1000,671        },672      }));673    });674    it('should import with updated expire times', function() {675      cache.put('key1', 'value1', 500);676      cache.put('key2', 'value2', 1000);677      var exportedJson = cache.exportJson();678      var tickAmount = 750;679      clock.tick(tickAmount);680      cache.importJson(exportedJson);681      expect(cache.exportJson()).to.equal(JSON.stringify({682        key2: {683          value: 'value2',684          expire: START_TIME + tickAmount + 250,685        },686      }));687    });688    it('should return the new size', function() {689      cache.put('key1', 'value1', 500);690      var exportedJson = cache.exportJson();691      cache.clear();692      cache.put('key2', 'value2', 1000);693      expect(cache.size()).to.equal(1);694      var size = cache.importJson(exportedJson);695      expect(size).to.equal(2);696      expect(cache.size()).to.equal(2);697    });698  });699  describe('Cache()', function() {700    it('should return a new cache instance when called', function() {701      var cache1 = new Cache(),702        cache2 = new Cache();703      cache1.put('key', 'value1');704      expect(cache1.keys()).to.deep.equal(['key']);705      expect(cache2.keys()).to.deep.equal([]);706      cache2.put('key', 'value2');707      expect(cache1.get('key')).to.equal('value1');708      expect(cache2.get('key')).to.equal('value2');709    });710  });...

Full Screen

Full Screen

cache-offline-coverage.js

Source:cache-offline-coverage.js Github

copy

Full Screen

1/*2YUI 3.7.3 (build 5687)3Copyright 2012 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7if (typeof _yuitest_coverage == "undefined"){8    _yuitest_coverage = {};9    _yuitest_coverline = function(src, line){10        var coverage = _yuitest_coverage[src];11        if (!coverage.lines[line]){12            coverage.calledLines++;13        }14        coverage.lines[line]++;15    };16    _yuitest_coverfunc = function(src, name, line){17        var coverage = _yuitest_coverage[src],18            funcId = name + ":" + line;19        if (!coverage.functions[funcId]){20            coverage.calledFunctions++;21        }22        coverage.functions[funcId]++;23    };24}25_yuitest_coverage["build/cache-offline/cache-offline.js"] = {26    lines: {},27    functions: {},28    coveredLines: 0,29    calledLines: 0,30    coveredFunctions: 0,31    calledFunctions: 0,32    path: "build/cache-offline/cache-offline.js",33    code: []34};35_yuitest_coverage["build/cache-offline/cache-offline.js"].code=["YUI.add('cache-offline', function (Y, NAME) {","","/**"," * Provides a Cache subclass which uses HTML5 `localStorage` for persistence."," * "," * @module cache"," * @submodule cache-offline"," */","","/**"," * Extends Cache utility with offline functionality."," * @class CacheOffline"," * @extends Cache"," * @constructor"," */","function CacheOffline() {","    CacheOffline.superclass.constructor.apply(this, arguments);","}","","var localStorage = null,","    JSON = Y.JSON;","","// Bug 2529572","try {","    localStorage = Y.config.win.localStorage;","}","catch(e) {","}","","/////////////////////////////////////////////////////////////////////////////","//","// CacheOffline events","//","/////////////////////////////////////////////////////////////////////////////","","/**","* @event error","* @description Fired when an entry could not be added, most likely due to","* exceeded browser quota.","* <dl>","* <dt>error (Object)</dt> <dd>The error object.</dd>","* </dl>","*/","","/////////////////////////////////////////////////////////////////////////////","//","// CacheOffline static","//","/////////////////////////////////////////////////////////////////////////////","Y.mix(CacheOffline, {","    /**","     * Class name.","     *","     * @property NAME","     * @type String","     * @static","     * @final","     * @value \"cacheOffline\"","     */","    NAME: \"cacheOffline\",","","    ATTRS: {","        /////////////////////////////////////////////////////////////////////////////","        //","        // CacheOffline Attributes","        //","        /////////////////////////////////////////////////////////////////////////////","","        /**","        * @attribute sandbox","        * @description A string that must be passed in via the constructor.","        * This identifier is used to sandbox one cache instance's entries","        * from another. Calling the cache instance's flush and length methods","        * or get(\"entries\") will apply to only these sandboxed entries.","        * @type String","        * @default \"default\"","        * @initOnly","        */","        sandbox: {","            value: \"default\",","            writeOnce: \"initOnly\"","        },","","        /**","        * @attribute expires","        * @description Absolute Date when data expires or","        * relative number of milliseconds. Zero disables expiration.","        * @type Date | Number","        * @default 86400000 (one day)","        */","        expires: {","            value: 86400000","        },","","        /**","        * @attribute max","        * @description Disabled.","        * @readOnly","        * @default null","        */","        max: {","            value: null,","            readOnly: true","        },","","        /**","        * @attribute uniqueKeys","        * @description Always true for CacheOffline.","        * @readOnly","        * @default true","        */","        uniqueKeys: {","            value: true,","            readOnly: true,","            setter: function() {","                return true;","            }","        }","    },","","    /**","     * Removes all items from all sandboxes. Useful if localStorage has","     * exceeded quota. Only supported on browsers that implement HTML 5","     * localStorage.","     *","     * @method flushAll","     * @static","     */","    flushAll: function() {","        var store = localStorage, key;","        if(store) {","            if(store.clear) {","                store.clear();","            }","            // FF2.x and FF3.0.x","            else {","                for (key in store) {","                    if (store.hasOwnProperty(key)) {","                        store.removeItem(key);","                        delete store[key];","                    }","                }","            }","        }","        else {","        }","    }","});","","Y.extend(CacheOffline, Y.Cache, localStorage ? {","/////////////////////////////////////////////////////////////////////////////","//","// Offline is supported","//","/////////////////////////////////////////////////////////////////////////////","","    /////////////////////////////////////////////////////////////////////////////","    //","    // CacheOffline protected methods","    //","    /////////////////////////////////////////////////////////////////////////////","    /**","     * Always return null.","     *","     * @method _setMax","     * @protected","     */","    _setMax: function(value) {","        return null;","    },","","    /**","     * Gets size.","     *","     * @method _getSize","     * @protected","     */","    _getSize: function() {","        var count = 0,","            i=0,","            l=localStorage.length;","        for(; i<l; ++i) {","            // Match sandbox id","            if(localStorage.key(i).indexOf(this.get(\"sandbox\")) === 0) {","                count++;","            }","        }","        return count;","    },","","    /**","     * Gets all entries.","     *","     * @method _getEntries","     * @protected","     */","    _getEntries: function() {","        var entries = [],","            i=0,","            l=localStorage.length,","            sandbox = this.get(\"sandbox\");","        for(; i<l; ++i) {","            // Match sandbox id","            if(localStorage.key(i).indexOf(sandbox) === 0) {","                entries[i] = JSON.parse(localStorage.key(i).substring(sandbox.length));","            }","        }","        return entries;","    },","","    /**","     * Adds entry to cache.","     *","     * @method _defAddFn","     * @param e {Event.Facade} Event Facade with the following properties:","     * <dl>","     * <dt>entry (Object)</dt> <dd>The cached entry.</dd>","     * </dl>","     * @protected","     */","    _defAddFn: function(e) {","        var entry = e.entry,","            request = entry.request,","            cached = entry.cached,","            expires = entry.expires;","","        // Convert Dates to msecs on the way into localStorage","        entry.cached = cached.getTime();","        entry.expires = expires ? expires.getTime() : expires;","","        try {","            localStorage.setItem(this.get(\"sandbox\")+JSON.stringify({\"request\":request}), JSON.stringify(entry));","        }","        catch(error) {","            this.fire(\"error\", {error:error});","        }","    },","","    /**","     * Flushes cache.","     *","     * @method _defFlushFn","     * @param e {Event.Facade} Event Facade object.","     * @protected","     */","    _defFlushFn: function(e) {","        var key,","            i=localStorage.length-1;","        for(; i>-1; --i) {","            // Match sandbox id","            key = localStorage.key(i);","            if(key.indexOf(this.get(\"sandbox\")) === 0) {","                localStorage.removeItem(key);","            }","        }","    },","","    /////////////////////////////////////////////////////////////////////////////","    //","    // CacheOffline public methods","    //","    /////////////////////////////////////////////////////////////////////////////","    /**","     * Adds a new entry to the cache of the format","     * {request:request, response:response, cached:cached, expires: expires}.","     *","     * @method add","     * @param request {Object} Request value must be a String or JSON.","     * @param response {Object} Response value must be a String or JSON.","     */","","    /**","     * Retrieves cached object for given request, if available.","     * Returns null if there is no cache match.","     *","     * @method retrieve","     * @param request {Object} Request object.","     * @return {Object} Cached object with the properties request, response,","     * and expires, or null.","     */","    retrieve: function(request) {","        this.fire(\"request\", {request: request});","","        var entry, expires, sandboxedrequest;","","        try {","            sandboxedrequest = this.get(\"sandbox\")+JSON.stringify({\"request\":request});","            try {","                entry = JSON.parse(localStorage.getItem(sandboxedrequest));","            }","            catch(e) {","            }","        }","        catch(e2) {","        }","","        if(entry) {","            // Convert msecs to Dates on the way out of localStorage","            entry.cached = new Date(entry.cached);","            expires = entry.expires;","            expires = !expires ? null : new Date(expires);","            entry.expires = expires;","","            if(this._isMatch(request, entry)) {","                this.fire(\"retrieve\", {entry: entry});","                return entry;","            }","        }","        return null;","    }","} :","/////////////////////////////////////////////////////////////////////////////","//","// Offline is not supported","//","/////////////////////////////////////////////////////////////////////////////","{","    /**","     * Always return null.","     *","     * @method _setMax","     * @protected","     */","    _setMax: function(value) {","        return null;","    }","});","","","Y.CacheOffline = CacheOffline;","","","}, '3.7.3', {\"requires\": [\"cache-base\", \"json\"]});"];36_yuitest_coverage["build/cache-offline/cache-offline.js"].lines = {"1":0,"16":0,"17":0,"20":0,"24":0,"25":0,"50":0,"116":0,"130":0,"131":0,"132":0,"133":0,"137":0,"138":0,"139":0,"140":0,"150":0,"169":0,"179":0,"182":0,"184":0,"185":0,"188":0,"198":0,"202":0,"204":0,"205":0,"208":0,"222":0,"228":0,"229":0,"231":0,"232":0,"235":0,"247":0,"249":0,"251":0,"252":0,"253":0,"282":0,"284":0,"286":0,"287":0,"288":0,"289":0,"297":0,"299":0,"300":0,"301":0,"302":0,"304":0,"305":0,"306":0,"309":0,"325":0,"330":0};37_yuitest_coverage["build/cache-offline/cache-offline.js"].functions = {"CacheOffline:16":0,"setter:115":0,"flushAll:129":0,"_setMax:168":0,"_getSize:178":0,"_getEntries:197":0,"_defAddFn:221":0,"_defFlushFn:246":0,"retrieve:281":0,"_setMax:324":0,"(anonymous 1):1":0};38_yuitest_coverage["build/cache-offline/cache-offline.js"].coveredLines = 56;39_yuitest_coverage["build/cache-offline/cache-offline.js"].coveredFunctions = 11;40_yuitest_coverline("build/cache-offline/cache-offline.js", 1);41YUI.add('cache-offline', function (Y, NAME) {42/**43 * Provides a Cache subclass which uses HTML5 `localStorage` for persistence.44 * 45 * @module cache46 * @submodule cache-offline47 */48/**49 * Extends Cache utility with offline functionality.50 * @class CacheOffline51 * @extends Cache52 * @constructor53 */54_yuitest_coverfunc("build/cache-offline/cache-offline.js", "(anonymous 1)", 1);55_yuitest_coverline("build/cache-offline/cache-offline.js", 16);56function CacheOffline() {57    _yuitest_coverfunc("build/cache-offline/cache-offline.js", "CacheOffline", 16);58_yuitest_coverline("build/cache-offline/cache-offline.js", 17);59CacheOffline.superclass.constructor.apply(this, arguments);60}61_yuitest_coverline("build/cache-offline/cache-offline.js", 20);62var localStorage = null,63    JSON = Y.JSON;64// Bug 252957265_yuitest_coverline("build/cache-offline/cache-offline.js", 24);66try {67    _yuitest_coverline("build/cache-offline/cache-offline.js", 25);68localStorage = Y.config.win.localStorage;69}70catch(e) {71}72/////////////////////////////////////////////////////////////////////////////73//74// CacheOffline events75//76/////////////////////////////////////////////////////////////////////////////77/**78* @event error79* @description Fired when an entry could not be added, most likely due to80* exceeded browser quota.81* <dl>82* <dt>error (Object)</dt> <dd>The error object.</dd>83* </dl>84*/85/////////////////////////////////////////////////////////////////////////////86//87// CacheOffline static88//89/////////////////////////////////////////////////////////////////////////////90_yuitest_coverline("build/cache-offline/cache-offline.js", 50);91Y.mix(CacheOffline, {92    /**93     * Class name.94     *95     * @property NAME96     * @type String97     * @static98     * @final99     * @value "cacheOffline"100     */101    NAME: "cacheOffline",102    ATTRS: {103        /////////////////////////////////////////////////////////////////////////////104        //105        // CacheOffline Attributes106        //107        /////////////////////////////////////////////////////////////////////////////108        /**109        * @attribute sandbox110        * @description A string that must be passed in via the constructor.111        * This identifier is used to sandbox one cache instance's entries112        * from another. Calling the cache instance's flush and length methods113        * or get("entries") will apply to only these sandboxed entries.114        * @type String115        * @default "default"116        * @initOnly117        */118        sandbox: {119            value: "default",120            writeOnce: "initOnly"121        },122        /**123        * @attribute expires124        * @description Absolute Date when data expires or125        * relative number of milliseconds. Zero disables expiration.126        * @type Date | Number127        * @default 86400000 (one day)128        */129        expires: {130            value: 86400000131        },132        /**133        * @attribute max134        * @description Disabled.135        * @readOnly136        * @default null137        */138        max: {139            value: null,140            readOnly: true141        },142        /**143        * @attribute uniqueKeys144        * @description Always true for CacheOffline.145        * @readOnly146        * @default true147        */148        uniqueKeys: {149            value: true,150            readOnly: true,151            setter: function() {152                _yuitest_coverfunc("build/cache-offline/cache-offline.js", "setter", 115);153_yuitest_coverline("build/cache-offline/cache-offline.js", 116);154return true;155            }156        }157    },158    /**159     * Removes all items from all sandboxes. Useful if localStorage has160     * exceeded quota. Only supported on browsers that implement HTML 5161     * localStorage.162     *163     * @method flushAll164     * @static165     */166    flushAll: function() {167        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "flushAll", 129);168_yuitest_coverline("build/cache-offline/cache-offline.js", 130);169var store = localStorage, key;170        _yuitest_coverline("build/cache-offline/cache-offline.js", 131);171if(store) {172            _yuitest_coverline("build/cache-offline/cache-offline.js", 132);173if(store.clear) {174                _yuitest_coverline("build/cache-offline/cache-offline.js", 133);175store.clear();176            }177            // FF2.x and FF3.0.x178            else {179                _yuitest_coverline("build/cache-offline/cache-offline.js", 137);180for (key in store) {181                    _yuitest_coverline("build/cache-offline/cache-offline.js", 138);182if (store.hasOwnProperty(key)) {183                        _yuitest_coverline("build/cache-offline/cache-offline.js", 139);184store.removeItem(key);185                        _yuitest_coverline("build/cache-offline/cache-offline.js", 140);186delete store[key];187                    }188                }189            }190        }191        else {192        }193    }194});195_yuitest_coverline("build/cache-offline/cache-offline.js", 150);196Y.extend(CacheOffline, Y.Cache, localStorage ? {197/////////////////////////////////////////////////////////////////////////////198//199// Offline is supported200//201/////////////////////////////////////////////////////////////////////////////202    /////////////////////////////////////////////////////////////////////////////203    //204    // CacheOffline protected methods205    //206    /////////////////////////////////////////////////////////////////////////////207    /**208     * Always return null.209     *210     * @method _setMax211     * @protected212     */213    _setMax: function(value) {214        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "_setMax", 168);215_yuitest_coverline("build/cache-offline/cache-offline.js", 169);216return null;217    },218    /**219     * Gets size.220     *221     * @method _getSize222     * @protected223     */224    _getSize: function() {225        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "_getSize", 178);226_yuitest_coverline("build/cache-offline/cache-offline.js", 179);227var count = 0,228            i=0,229            l=localStorage.length;230        _yuitest_coverline("build/cache-offline/cache-offline.js", 182);231for(; i<l; ++i) {232            // Match sandbox id233            _yuitest_coverline("build/cache-offline/cache-offline.js", 184);234if(localStorage.key(i).indexOf(this.get("sandbox")) === 0) {235                _yuitest_coverline("build/cache-offline/cache-offline.js", 185);236count++;237            }238        }239        _yuitest_coverline("build/cache-offline/cache-offline.js", 188);240return count;241    },242    /**243     * Gets all entries.244     *245     * @method _getEntries246     * @protected247     */248    _getEntries: function() {249        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "_getEntries", 197);250_yuitest_coverline("build/cache-offline/cache-offline.js", 198);251var entries = [],252            i=0,253            l=localStorage.length,254            sandbox = this.get("sandbox");255        _yuitest_coverline("build/cache-offline/cache-offline.js", 202);256for(; i<l; ++i) {257            // Match sandbox id258            _yuitest_coverline("build/cache-offline/cache-offline.js", 204);259if(localStorage.key(i).indexOf(sandbox) === 0) {260                _yuitest_coverline("build/cache-offline/cache-offline.js", 205);261entries[i] = JSON.parse(localStorage.key(i).substring(sandbox.length));262            }263        }264        _yuitest_coverline("build/cache-offline/cache-offline.js", 208);265return entries;266    },267    /**268     * Adds entry to cache.269     *270     * @method _defAddFn271     * @param e {Event.Facade} Event Facade with the following properties:272     * <dl>273     * <dt>entry (Object)</dt> <dd>The cached entry.</dd>274     * </dl>275     * @protected276     */277    _defAddFn: function(e) {278        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "_defAddFn", 221);279_yuitest_coverline("build/cache-offline/cache-offline.js", 222);280var entry = e.entry,281            request = entry.request,282            cached = entry.cached,283            expires = entry.expires;284        // Convert Dates to msecs on the way into localStorage285        _yuitest_coverline("build/cache-offline/cache-offline.js", 228);286entry.cached = cached.getTime();287        _yuitest_coverline("build/cache-offline/cache-offline.js", 229);288entry.expires = expires ? expires.getTime() : expires;289        _yuitest_coverline("build/cache-offline/cache-offline.js", 231);290try {291            _yuitest_coverline("build/cache-offline/cache-offline.js", 232);292localStorage.setItem(this.get("sandbox")+JSON.stringify({"request":request}), JSON.stringify(entry));293        }294        catch(error) {295            _yuitest_coverline("build/cache-offline/cache-offline.js", 235);296this.fire("error", {error:error});297        }298    },299    /**300     * Flushes cache.301     *302     * @method _defFlushFn303     * @param e {Event.Facade} Event Facade object.304     * @protected305     */306    _defFlushFn: function(e) {307        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "_defFlushFn", 246);308_yuitest_coverline("build/cache-offline/cache-offline.js", 247);309var key,310            i=localStorage.length-1;311        _yuitest_coverline("build/cache-offline/cache-offline.js", 249);312for(; i>-1; --i) {313            // Match sandbox id314            _yuitest_coverline("build/cache-offline/cache-offline.js", 251);315key = localStorage.key(i);316            _yuitest_coverline("build/cache-offline/cache-offline.js", 252);317if(key.indexOf(this.get("sandbox")) === 0) {318                _yuitest_coverline("build/cache-offline/cache-offline.js", 253);319localStorage.removeItem(key);320            }321        }322    },323    /////////////////////////////////////////////////////////////////////////////324    //325    // CacheOffline public methods326    //327    /////////////////////////////////////////////////////////////////////////////328    /**329     * Adds a new entry to the cache of the format330     * {request:request, response:response, cached:cached, expires: expires}.331     *332     * @method add333     * @param request {Object} Request value must be a String or JSON.334     * @param response {Object} Response value must be a String or JSON.335     */336    /**337     * Retrieves cached object for given request, if available.338     * Returns null if there is no cache match.339     *340     * @method retrieve341     * @param request {Object} Request object.342     * @return {Object} Cached object with the properties request, response,343     * and expires, or null.344     */345    retrieve: function(request) {346        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "retrieve", 281);347_yuitest_coverline("build/cache-offline/cache-offline.js", 282);348this.fire("request", {request: request});349        _yuitest_coverline("build/cache-offline/cache-offline.js", 284);350var entry, expires, sandboxedrequest;351        _yuitest_coverline("build/cache-offline/cache-offline.js", 286);352try {353            _yuitest_coverline("build/cache-offline/cache-offline.js", 287);354sandboxedrequest = this.get("sandbox")+JSON.stringify({"request":request});355            _yuitest_coverline("build/cache-offline/cache-offline.js", 288);356try {357                _yuitest_coverline("build/cache-offline/cache-offline.js", 289);358entry = JSON.parse(localStorage.getItem(sandboxedrequest));359            }360            catch(e) {361            }362        }363        catch(e2) {364        }365        _yuitest_coverline("build/cache-offline/cache-offline.js", 297);366if(entry) {367            // Convert msecs to Dates on the way out of localStorage368            _yuitest_coverline("build/cache-offline/cache-offline.js", 299);369entry.cached = new Date(entry.cached);370            _yuitest_coverline("build/cache-offline/cache-offline.js", 300);371expires = entry.expires;372            _yuitest_coverline("build/cache-offline/cache-offline.js", 301);373expires = !expires ? null : new Date(expires);374            _yuitest_coverline("build/cache-offline/cache-offline.js", 302);375entry.expires = expires;376            _yuitest_coverline("build/cache-offline/cache-offline.js", 304);377if(this._isMatch(request, entry)) {378                _yuitest_coverline("build/cache-offline/cache-offline.js", 305);379this.fire("retrieve", {entry: entry});380                _yuitest_coverline("build/cache-offline/cache-offline.js", 306);381return entry;382            }383        }384        _yuitest_coverline("build/cache-offline/cache-offline.js", 309);385return null;386    }387} :388/////////////////////////////////////////////////////////////////////////////389//390// Offline is not supported391//392/////////////////////////////////////////////////////////////////////////////393{394    /**395     * Always return null.396     *397     * @method _setMax398     * @protected399     */400    _setMax: function(value) {401        _yuitest_coverfunc("build/cache-offline/cache-offline.js", "_setMax", 324);402_yuitest_coverline("build/cache-offline/cache-offline.js", 325);403return null;404    }405});406_yuitest_coverline("build/cache-offline/cache-offline.js", 330);407Y.CacheOffline = CacheOffline;...

Full Screen

Full Screen

datasource-cache-coverage.js

Source:datasource-cache-coverage.js Github

copy

Full Screen

1/*2YUI 3.7.3 (build 5687)3Copyright 2012 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7if (typeof _yuitest_coverage == "undefined"){8    _yuitest_coverage = {};9    _yuitest_coverline = function(src, line){10        var coverage = _yuitest_coverage[src];11        if (!coverage.lines[line]){12            coverage.calledLines++;13        }14        coverage.lines[line]++;15    };16    _yuitest_coverfunc = function(src, name, line){17        var coverage = _yuitest_coverage[src],18            funcId = name + ":" + line;19        if (!coverage.functions[funcId]){20            coverage.calledFunctions++;21        }22        coverage.functions[funcId]++;23    };24}25_yuitest_coverage["build/datasource-cache/datasource-cache.js"] = {26    lines: {},27    functions: {},28    coveredLines: 0,29    calledLines: 0,30    coveredFunctions: 0,31    calledFunctions: 0,32    path: "build/datasource-cache/datasource-cache.js",33    code: []34};35_yuitest_coverage["build/datasource-cache/datasource-cache.js"].code=["YUI.add('datasource-cache', function (Y, NAME) {","","/**"," * Plugs DataSource with caching functionality."," *"," * @module datasource"," * @submodule datasource-cache"," */","","/**"," * DataSourceCache extension binds Cache to DataSource."," * @class DataSourceCacheExtension"," */","var DataSourceCacheExtension = function() {","};","","Y.mix(DataSourceCacheExtension, {","    /**","     * The namespace for the plugin. This will be the property on the host which","     * references the plugin instance.","     *","     * @property NS","     * @type String","     * @static","     * @final","     * @value \"cache\"","     */","    NS: \"cache\",","","    /**","     * Class name.","     *","     * @property NAME","     * @type String","     * @static","     * @final","     * @value \"dataSourceCacheExtension\"","     */","    NAME: \"dataSourceCacheExtension\"","});","","DataSourceCacheExtension.prototype = {","    /**","    * Internal init() handler.","    *","    * @method initializer","    * @param config {Object} Config object.","    * @private","    */","    initializer: function(config) {","        this.doBefore(\"_defRequestFn\", this._beforeDefRequestFn);","        this.doBefore(\"_defResponseFn\", this._beforeDefResponseFn);","    },","","    /**","     * First look for cached response, then send request to live data.","     *","     * @method _beforeDefRequestFn","     * @param e {Event.Facade} Event Facade with the following properties:","     * <dl>","     * <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>","     * <dt>request (Object)</dt> <dd>The request.</dd>","     * <dt>callback (Object)</dt> <dd>The callback object.</dd>","     * <dt>cfg (Object)</dt> <dd>Configuration object.</dd>","     * </dl>","     * @protected","     */","    _beforeDefRequestFn: function(e) {","        // Is response already in the Cache?","        var entry = (this.retrieve(e.request)) || null,","            payload = e.details[0];","","        if (entry && entry.response) {","            payload.cached   = entry.cached;","            payload.response = entry.response;","            payload.data     = entry.data;","","            this.get(\"host\").fire(\"response\", payload);","","            return new Y.Do.Halt(\"DataSourceCache extension halted _defRequestFn\");","        }","    },","","    /**","     * Adds data to cache before returning data.","     *","     * @method _beforeDefResponseFn","     * @param e {Event.Facade} Event Facade with the following properties:","     * <dl>","     * <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>","     * <dt>request (Object)</dt> <dd>The request.</dd>","     * <dt>callback (Object)</dt> <dd>The callback object with the following properties:","     *     <dl>","     *         <dt>success (Function)</dt> <dd>Success handler.</dd>","     *         <dt>failure (Function)</dt> <dd>Failure handler.</dd>","     *     </dl>","     * </dd>","     * <dt>data (Object)</dt> <dd>Raw data.</dd>","     * <dt>response (Object)</dt> <dd>Normalized response object with the following properties:","     *     <dl>","     *         <dt>cached (Object)</dt> <dd>True when response is cached.</dd>","     *         <dt>results (Object)</dt> <dd>Parsed results.</dd>","     *         <dt>meta (Object)</dt> <dd>Parsed meta data.</dd>","     *         <dt>error (Object)</dt> <dd>Error object.</dd>","     *     </dl>","     * </dd>","     * <dt>cfg (Object)</dt> <dd>Configuration object.</dd>","     * </dl>","     * @protected","     */","     _beforeDefResponseFn: function(e) {","        // Add to Cache before returning","        if(e.response && !e.cached) {","            this.add(e.request, e.response);","        }","     }","};","","Y.namespace(\"Plugin\").DataSourceCacheExtension = DataSourceCacheExtension;","","","","/**"," * DataSource plugin adds cache functionality."," * @class DataSourceCache"," * @extends Cache"," * @uses Plugin.Base, DataSourceCachePlugin"," */","function DataSourceCache(config) {","    var cache = config && config.cache ? config.cache : Y.Cache,","        tmpclass = Y.Base.create(\"dataSourceCache\", cache, [Y.Plugin.Base, Y.Plugin.DataSourceCacheExtension]),","        tmpinstance = new tmpclass(config);","    tmpclass.NS = \"tmpClass\";","    return tmpinstance;","}","","Y.mix(DataSourceCache, {","    /**","     * The namespace for the plugin. This will be the property on the host which","     * references the plugin instance.","     *","     * @property NS","     * @type String","     * @static","     * @final","     * @value \"cache\"","     */","    NS: \"cache\",","","    /**","     * Class name.","     *","     * @property NAME","     * @type String","     * @static","     * @final","     * @value \"dataSourceCache\"","     */","    NAME: \"dataSourceCache\"","});","","","Y.namespace(\"Plugin\").DataSourceCache = DataSourceCache;","","","}, '3.7.3', {\"requires\": [\"datasource-local\", \"plugin\", \"cache-base\"]});"];36_yuitest_coverage["build/datasource-cache/datasource-cache.js"].lines = {"1":0,"14":0,"17":0,"42":0,"51":0,"52":0,"70":0,"73":0,"74":0,"75":0,"76":0,"78":0,"80":0,"113":0,"114":0,"119":0,"129":0,"130":0,"133":0,"134":0,"137":0,"163":0};37_yuitest_coverage["build/datasource-cache/datasource-cache.js"].functions = {"initializer:50":0,"_beforeDefRequestFn:68":0,"_beforeDefResponseFn:111":0,"DataSourceCache:129":0,"(anonymous 1):1":0};38_yuitest_coverage["build/datasource-cache/datasource-cache.js"].coveredLines = 22;39_yuitest_coverage["build/datasource-cache/datasource-cache.js"].coveredFunctions = 5;40_yuitest_coverline("build/datasource-cache/datasource-cache.js", 1);41YUI.add('datasource-cache', function (Y, NAME) {42/**43 * Plugs DataSource with caching functionality.44 *45 * @module datasource46 * @submodule datasource-cache47 */48/**49 * DataSourceCache extension binds Cache to DataSource.50 * @class DataSourceCacheExtension51 */52_yuitest_coverfunc("build/datasource-cache/datasource-cache.js", "(anonymous 1)", 1);53_yuitest_coverline("build/datasource-cache/datasource-cache.js", 14);54var DataSourceCacheExtension = function() {55};56_yuitest_coverline("build/datasource-cache/datasource-cache.js", 17);57Y.mix(DataSourceCacheExtension, {58    /**59     * The namespace for the plugin. This will be the property on the host which60     * references the plugin instance.61     *62     * @property NS63     * @type String64     * @static65     * @final66     * @value "cache"67     */68    NS: "cache",69    /**70     * Class name.71     *72     * @property NAME73     * @type String74     * @static75     * @final76     * @value "dataSourceCacheExtension"77     */78    NAME: "dataSourceCacheExtension"79});80_yuitest_coverline("build/datasource-cache/datasource-cache.js", 42);81DataSourceCacheExtension.prototype = {82    /**83    * Internal init() handler.84    *85    * @method initializer86    * @param config {Object} Config object.87    * @private88    */89    initializer: function(config) {90        _yuitest_coverfunc("build/datasource-cache/datasource-cache.js", "initializer", 50);91_yuitest_coverline("build/datasource-cache/datasource-cache.js", 51);92this.doBefore("_defRequestFn", this._beforeDefRequestFn);93        _yuitest_coverline("build/datasource-cache/datasource-cache.js", 52);94this.doBefore("_defResponseFn", this._beforeDefResponseFn);95    },96    /**97     * First look for cached response, then send request to live data.98     *99     * @method _beforeDefRequestFn100     * @param e {Event.Facade} Event Facade with the following properties:101     * <dl>102     * <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>103     * <dt>request (Object)</dt> <dd>The request.</dd>104     * <dt>callback (Object)</dt> <dd>The callback object.</dd>105     * <dt>cfg (Object)</dt> <dd>Configuration object.</dd>106     * </dl>107     * @protected108     */109    _beforeDefRequestFn: function(e) {110        // Is response already in the Cache?111        _yuitest_coverfunc("build/datasource-cache/datasource-cache.js", "_beforeDefRequestFn", 68);112_yuitest_coverline("build/datasource-cache/datasource-cache.js", 70);113var entry = (this.retrieve(e.request)) || null,114            payload = e.details[0];115        _yuitest_coverline("build/datasource-cache/datasource-cache.js", 73);116if (entry && entry.response) {117            _yuitest_coverline("build/datasource-cache/datasource-cache.js", 74);118payload.cached   = entry.cached;119            _yuitest_coverline("build/datasource-cache/datasource-cache.js", 75);120payload.response = entry.response;121            _yuitest_coverline("build/datasource-cache/datasource-cache.js", 76);122payload.data     = entry.data;123            _yuitest_coverline("build/datasource-cache/datasource-cache.js", 78);124this.get("host").fire("response", payload);125            _yuitest_coverline("build/datasource-cache/datasource-cache.js", 80);126return new Y.Do.Halt("DataSourceCache extension halted _defRequestFn");127        }128    },129    /**130     * Adds data to cache before returning data.131     *132     * @method _beforeDefResponseFn133     * @param e {Event.Facade} Event Facade with the following properties:134     * <dl>135     * <dt>tId (Number)</dt> <dd>Unique transaction ID.</dd>136     * <dt>request (Object)</dt> <dd>The request.</dd>137     * <dt>callback (Object)</dt> <dd>The callback object with the following properties:138     *     <dl>139     *         <dt>success (Function)</dt> <dd>Success handler.</dd>140     *         <dt>failure (Function)</dt> <dd>Failure handler.</dd>141     *     </dl>142     * </dd>143     * <dt>data (Object)</dt> <dd>Raw data.</dd>144     * <dt>response (Object)</dt> <dd>Normalized response object with the following properties:145     *     <dl>146     *         <dt>cached (Object)</dt> <dd>True when response is cached.</dd>147     *         <dt>results (Object)</dt> <dd>Parsed results.</dd>148     *         <dt>meta (Object)</dt> <dd>Parsed meta data.</dd>149     *         <dt>error (Object)</dt> <dd>Error object.</dd>150     *     </dl>151     * </dd>152     * <dt>cfg (Object)</dt> <dd>Configuration object.</dd>153     * </dl>154     * @protected155     */156     _beforeDefResponseFn: function(e) {157        // Add to Cache before returning158        _yuitest_coverfunc("build/datasource-cache/datasource-cache.js", "_beforeDefResponseFn", 111);159_yuitest_coverline("build/datasource-cache/datasource-cache.js", 113);160if(e.response && !e.cached) {161            _yuitest_coverline("build/datasource-cache/datasource-cache.js", 114);162this.add(e.request, e.response);163        }164     }165};166_yuitest_coverline("build/datasource-cache/datasource-cache.js", 119);167Y.namespace("Plugin").DataSourceCacheExtension = DataSourceCacheExtension;168/**169 * DataSource plugin adds cache functionality.170 * @class DataSourceCache171 * @extends Cache172 * @uses Plugin.Base, DataSourceCachePlugin173 */174_yuitest_coverline("build/datasource-cache/datasource-cache.js", 129);175function DataSourceCache(config) {176    _yuitest_coverfunc("build/datasource-cache/datasource-cache.js", "DataSourceCache", 129);177_yuitest_coverline("build/datasource-cache/datasource-cache.js", 130);178var cache = config && config.cache ? config.cache : Y.Cache,179        tmpclass = Y.Base.create("dataSourceCache", cache, [Y.Plugin.Base, Y.Plugin.DataSourceCacheExtension]),180        tmpinstance = new tmpclass(config);181    _yuitest_coverline("build/datasource-cache/datasource-cache.js", 133);182tmpclass.NS = "tmpClass";183    _yuitest_coverline("build/datasource-cache/datasource-cache.js", 134);184return tmpinstance;185}186_yuitest_coverline("build/datasource-cache/datasource-cache.js", 137);187Y.mix(DataSourceCache, {188    /**189     * The namespace for the plugin. This will be the property on the host which190     * references the plugin instance.191     *192     * @property NS193     * @type String194     * @static195     * @final196     * @value "cache"197     */198    NS: "cache",199    /**200     * Class name.201     *202     * @property NAME203     * @type String204     * @static205     * @final206     * @value "dataSourceCache"207     */208    NAME: "dataSourceCache"209});210_yuitest_coverline("build/datasource-cache/datasource-cache.js", 163);211Y.namespace("Plugin").DataSourceCache = DataSourceCache;...

Full Screen

Full Screen

cacheFactory.js

Source:cacheFactory.js Github

copy

Full Screen

1'use strict';2/**3 * @ngdoc service4 * @name $cacheFactory5 *6 * @description7 * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to8 * them.9 *10 * ```js11 *12 *  var cache = $cacheFactory('cacheId');13 *  expect($cacheFactory.get('cacheId')).toBe(cache);14 *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();15 *16 *  cache.put("key", "value");17 *  cache.put("another key", "another value");18 *19 *  // We've specified no options on creation20 *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});21 *22 * ```23 *24 *25 * @param {string} cacheId Name or id of the newly created cache.26 * @param {object=} options Options object that specifies the cache behavior. Properties:27 *28 *   - `{number=}` `capacity` — turns the cache into LRU cache.29 *30 * @returns {object} Newly created cache object with the following set of methods:31 *32 * - `{object}` `info()` — Returns id, size, and options of cache.33 * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns34 *   it.35 * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.36 * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.37 * - `{void}` `removeAll()` — Removes all cached values.38 * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.39 *40 * @example41   <example module="cacheExampleApp">42     <file name="index.html">43       <div ng-controller="CacheController">44         <input ng-model="newCacheKey" placeholder="Key">45         <input ng-model="newCacheValue" placeholder="Value">46         <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>47         <p ng-if="keys.length">Cached Values</p>48         <div ng-repeat="key in keys">49           <span ng-bind="key"></span>50           <span>: </span>51           <b ng-bind="cache.get(key)"></b>52         </div>53         <p>Cache Info</p>54         <div ng-repeat="(key, value) in cache.info()">55           <span ng-bind="key"></span>56           <span>: </span>57           <b ng-bind="value"></b>58         </div>59       </div>60     </file>61     <file name="script.js">62       angular.module('cacheExampleApp', []).63         controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {64           $scope.keys = [];65           $scope.cache = $cacheFactory('cacheId');66           $scope.put = function(key, value) {67             if ($scope.cache.get(key) === undefined) {68               $scope.keys.push(key);69             }70             $scope.cache.put(key, value === undefined ? null : value);71           };72         }]);73     </file>74     <file name="style.css">75       p {76         margin: 10px 0 3px;77       }78     </file>79   </example>80 */81function $CacheFactoryProvider() {82  this.$get = function() {83    var caches = {};84    function cacheFactory(cacheId, options) {85      if (cacheId in caches) {86        throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);87      }88      var size = 0,89          stats = extend({}, options, {id: cacheId}),90          data = {},91          capacity = (options && options.capacity) || Number.MAX_VALUE,92          lruHash = {},93          freshEnd = null,94          staleEnd = null;95      /**96       * @ngdoc type97       * @name $cacheFactory.Cache98       *99       * @description100       * A cache object used to store and retrieve data, primarily used by101       * {@link $http $http} and the {@link ng.directive:script script} directive to cache102       * templates and other data.103       *104       * ```js105       *  angular.module('superCache')106       *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {107       *      return $cacheFactory('super-cache');108       *    }]);109       * ```110       *111       * Example test:112       *113       * ```js114       *  it('should behave like a cache', inject(function(superCache) {115       *    superCache.put('key', 'value');116       *    superCache.put('another key', 'another value');117       *118       *    expect(superCache.info()).toEqual({119       *      id: 'super-cache',120       *      size: 2121       *    });122       *123       *    superCache.remove('another key');124       *    expect(superCache.get('another key')).toBeUndefined();125       *126       *    superCache.removeAll();127       *    expect(superCache.info()).toEqual({128       *      id: 'super-cache',129       *      size: 0130       *    });131       *  }));132       * ```133       */134      return caches[cacheId] = {135        /**136         * @ngdoc method137         * @name $cacheFactory.Cache#put138         * @kind function139         *140         * @description141         * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be142         * retrieved later, and incrementing the size of the cache if the key was not already143         * present in the cache. If behaving like an LRU cache, it will also remove stale144         * entries from the set.145         *146         * It will not insert undefined values into the cache.147         *148         * @param {string} key the key under which the cached data is stored.149         * @param {*} value the value to store alongside the key. If it is undefined, the key150         *    will not be stored.151         * @returns {*} the value stored.152         */153        put: function(key, value) {154          if (capacity < Number.MAX_VALUE) {155            var lruEntry = lruHash[key] || (lruHash[key] = {key: key});156            refresh(lruEntry);157          }158          if (isUndefined(value)) return;159          if (!(key in data)) size++;160          data[key] = value;161          if (size > capacity) {162            this.remove(staleEnd.key);163          }164          return value;165        },166        /**167         * @ngdoc method168         * @name $cacheFactory.Cache#get169         * @kind function170         *171         * @description172         * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.173         *174         * @param {string} key the key of the data to be retrieved175         * @returns {*} the value stored.176         */177        get: function(key) {178          if (capacity < Number.MAX_VALUE) {179            var lruEntry = lruHash[key];180            if (!lruEntry) return;181            refresh(lruEntry);182          }183          return data[key];184        },185        /**186         * @ngdoc method187         * @name $cacheFactory.Cache#remove188         * @kind function189         *190         * @description191         * Removes an entry from the {@link $cacheFactory.Cache Cache} object.192         *193         * @param {string} key the key of the entry to be removed194         */195        remove: function(key) {196          if (capacity < Number.MAX_VALUE) {197            var lruEntry = lruHash[key];198            if (!lruEntry) return;199            if (lruEntry == freshEnd) freshEnd = lruEntry.p;200            if (lruEntry == staleEnd) staleEnd = lruEntry.n;201            link(lruEntry.n,lruEntry.p);202            delete lruHash[key];203          }204          delete data[key];205          size--;206        },207        /**208         * @ngdoc method209         * @name $cacheFactory.Cache#removeAll210         * @kind function211         *212         * @description213         * Clears the cache object of any entries.214         */215        removeAll: function() {216          data = {};217          size = 0;218          lruHash = {};219          freshEnd = staleEnd = null;220        },221        /**222         * @ngdoc method223         * @name $cacheFactory.Cache#destroy224         * @kind function225         *226         * @description227         * Destroys the {@link $cacheFactory.Cache Cache} object entirely,228         * removing it from the {@link $cacheFactory $cacheFactory} set.229         */230        destroy: function() {231          data = null;232          stats = null;233          lruHash = null;234          delete caches[cacheId];235        },236        /**237         * @ngdoc method238         * @name $cacheFactory.Cache#info239         * @kind function240         *241         * @description242         * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.243         *244         * @returns {object} an object with the following properties:245         *   <ul>246         *     <li>**id**: the id of the cache instance</li>247         *     <li>**size**: the number of entries kept in the cache instance</li>248         *     <li>**...**: any additional properties from the options object when creating the249         *       cache.</li>250         *   </ul>251         */252        info: function() {253          return extend({}, stats, {size: size});254        }255      };256      /**257       * makes the `entry` the freshEnd of the LRU linked list258       */259      function refresh(entry) {260        if (entry != freshEnd) {261          if (!staleEnd) {262            staleEnd = entry;263          } else if (staleEnd == entry) {264            staleEnd = entry.n;265          }266          link(entry.n, entry.p);267          link(entry, freshEnd);268          freshEnd = entry;269          freshEnd.n = null;270        }271      }272      /**273       * bidirectionally links two entries of the LRU linked list274       */275      function link(nextEntry, prevEntry) {276        if (nextEntry != prevEntry) {277          if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify278          if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify279        }280      }281    }282  /**283   * @ngdoc method284   * @name $cacheFactory#info285   *286   * @description287   * Get information about all the caches that have been created288   *289   * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`290   */291    cacheFactory.info = function() {292      var info = {};293      forEach(caches, function(cache, cacheId) {294        info[cacheId] = cache.info();295      });296      return info;297    };298  /**299   * @ngdoc method300   * @name $cacheFactory#get301   *302   * @description303   * Get access to a cache object by the `cacheId` used when it was created.304   *305   * @param {string} cacheId Name or id of a cache to access.306   * @returns {object} Cache object identified by the cacheId or undefined if no such cache.307   */308    cacheFactory.get = function(cacheId) {309      return caches[cacheId];310    };311    return cacheFactory;312  };313}314/**315 * @ngdoc service316 * @name $templateCache317 *318 * @description319 * The first time a template is used, it is loaded in the template cache for quick retrieval. You320 * can load templates directly into the cache in a `script` tag, or by consuming the321 * `$templateCache` service directly.322 *323 * Adding via the `script` tag:324 *325 * ```html326 *   <script type="text/ng-template" id="templateId.html">327 *     <p>This is the content of the template</p>328 *   </script>329 * ```330 *331 * **Note:** the `script` tag containing the template does not need to be included in the `head` of332 * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,333 * element with ng-app attribute), otherwise the template will be ignored.334 *335 * Adding via the `$templateCache` service:336 *337 * ```js338 * var myApp = angular.module('myApp', []);339 * myApp.run(function($templateCache) {340 *   $templateCache.put('templateId.html', 'This is the content of the template');341 * });342 * ```343 *344 * To retrieve the template later, simply use it in your HTML:345 * ```html346 * <div ng-include=" 'templateId.html' "></div>347 * ```348 *349 * or get it via Javascript:350 * ```js351 * $templateCache.get('templateId.html')352 * ```353 *354 * See {@link ng.$cacheFactory $cacheFactory}.355 *356 */357function $TemplateCacheProvider() {358  this.$get = ['$cacheFactory', function($cacheFactory) {359    return $cacheFactory('templates');360  }];...

Full Screen

Full Screen

cacheFactorySpec.js

Source:cacheFactorySpec.js Github

copy

Full Screen

1'use strict';2describe('$cacheFactory', function() {3  it('should be injected', inject(function($cacheFactory) {4    expect($cacheFactory).toBeDefined();5  }));6  it('should return a new cache whenever called', inject(function($cacheFactory) {7    var cache1 = $cacheFactory('cache1');8    var cache2 = $cacheFactory('cache2');9    expect(cache1).not.toEqual(cache2);10  }));11  it('should complain if the cache id is being reused', inject(function($cacheFactory) {12    $cacheFactory('cache1');13    expect(function() { $cacheFactory('cache1'); }).14      toThrowMinErr("$cacheFactory", "iid", "CacheId 'cache1' is already taken!");15  }));16  describe('info', function() {17    it('should provide info about all created caches', inject(function($cacheFactory) {18      expect($cacheFactory.info()).toEqual({});19      var cache1 = $cacheFactory('cache1');20      expect($cacheFactory.info()).toEqual({cache1: {id: 'cache1', size: 0}});21      cache1.put('foo', 'bar');22      expect($cacheFactory.info()).toEqual({cache1: {id: 'cache1', size: 1}});23    }));24  });25  describe('get', function() {26    it('should return a cache if looked up by id', inject(function($cacheFactory) {27      var cache1 = $cacheFactory('cache1'),28          cache2 = $cacheFactory('cache2');29      expect(cache1).not.toBe(cache2);30      expect(cache1).toBe($cacheFactory.get('cache1'));31      expect(cache2).toBe($cacheFactory.get('cache2'));32    }));33  });34  describe('cache', function() {35    var cache;36    beforeEach(inject(function($cacheFactory) {37      cache = $cacheFactory('test');38    }));39    describe('put, get & remove', function() {40      it('should add cache entries via add and retrieve them via get', inject(function($cacheFactory) {41        cache.put('key1', 'bar');42        cache.put('key2', {bar:'baz'});43        expect(cache.get('key2')).toEqual({bar:'baz'});44        expect(cache.get('key1')).toBe('bar');45      }));46      it('should ignore put if the value is undefined', inject(function($cacheFactory) {47        cache.put();48        cache.put('key1');49        cache.put('key2', undefined);50        expect(cache.info().size).toBe(0);51      }));52      it('should remove entries via remove', inject(function($cacheFactory) {53        cache.put('k1', 'foo');54        cache.put('k2', 'bar');55        cache.remove('k2');56        expect(cache.get('k1')).toBe('foo');57        expect(cache.get('k2')).toBeUndefined();58        cache.remove('k1');59        expect(cache.get('k1')).toBeUndefined();60        expect(cache.get('k2')).toBeUndefined();61      }));62      it('should return undefined when entry does not exist', inject(function($cacheFactory) {63        expect(cache.remove('non-existent')).toBeUndefined();64      }));65      it('should stringify keys', inject(function($cacheFactory) {66        cache.put('123', 'foo');67        cache.put(123, 'bar');68        expect(cache.get('123')).toBe('bar');69        expect(cache.info().size).toBe(1);70        cache.remove(123);71        expect(cache.info().size).toBe(0);72      }));73      it("should return value from put", inject(function($cacheFactory) {74        var obj = {};75        expect(cache.put('k1', obj)).toBe(obj);76      }));77    });78    describe('info', function() {79      it('should size increment with put and decrement with remove', inject(function($cacheFactory) {80        expect(cache.info().size).toBe(0);81        cache.put('foo', 'bar');82        expect(cache.info().size).toBe(1);83        cache.put('baz', 'boo');84        expect(cache.info().size).toBe(2);85        cache.remove('baz');86        expect(cache.info().size).toBe(1);87        cache.remove('foo');88        expect(cache.info().size).toBe(0);89      }));90      it('should return cache id', inject(function($cacheFactory) {91        expect(cache.info().id).toBe('test');92      }));93    });94    describe('removeAll', function() {95      it('should blow away all data', inject(function($cacheFactory) {96        cache.put('id1', 1);97        cache.put('id2', 2);98        cache.put('id3', 3);99        expect(cache.info().size).toBe(3);100        cache.removeAll();101        expect(cache.info().size).toBe(0);102        expect(cache.get('id1')).toBeUndefined();103        expect(cache.get('id2')).toBeUndefined();104        expect(cache.get('id3')).toBeUndefined();105      }));106    });107    describe('destroy', function() {108      it('should make the cache unusable and remove references to it from $cacheFactory', inject(function($cacheFactory) {109        cache.put('foo', 'bar');110        cache.destroy();111        expect(function() { cache.get('foo'); }).toThrow();112        expect(function() { cache.get('neverexisted'); }).toThrow();113        expect(function() { cache.put('foo', 'bar'); }).toThrow();114        expect($cacheFactory.get('test')).toBeUndefined();115        expect($cacheFactory.info()).toEqual({});116      }));117    });118  });119  describe('LRU cache', function() {120    it('should create cache with defined capacity', inject(function($cacheFactory) {121      var cache = $cacheFactory('cache1', {capacity: 5});122      expect(cache.info().size).toBe(0);123      for (var i = 0; i < 5; i++) {124        cache.put('id' + i, i);125      }126      expect(cache.info().size).toBe(5);127      cache.put('id5', 5);128      expect(cache.info().size).toBe(5);129      cache.put('id6', 6);130      expect(cache.info().size).toBe(5);131    }));132    describe('eviction', function() {133      var cache;134      beforeEach(inject(function($cacheFactory) {135        cache = $cacheFactory('cache1', {capacity: 2});136        cache.put('id0', 0);137        cache.put('id1', 1);138      }));139      it('should kick out the first entry on put', inject(function($cacheFactory) {140        cache.put('id2', 2);141        expect(cache.get('id0')).toBeUndefined();142        expect(cache.get('id1')).toBe(1);143        expect(cache.get('id2')).toBe(2);144      }));145      it('should refresh an entry via get', inject(function($cacheFactory) {146        cache.get('id0');147        cache.put('id2', 2);148        expect(cache.get('id0')).toBe(0);149        expect(cache.get('id1')).toBeUndefined();150        expect(cache.get('id2')).toBe(2);151      }));152      it('should refresh an entry via put', inject(function($cacheFactory) {153        cache.put('id0', '00');154        cache.put('id2', 2);155        expect(cache.get('id0')).toBe('00');156        expect(cache.get('id1')).toBeUndefined();157        expect(cache.get('id2')).toBe(2);158      }));159      it('should not purge an entry if another one was removed', inject(function($cacheFactory) {160        cache.remove('id1');161        cache.put('id2', 2);162        expect(cache.get('id0')).toBe(0);163        expect(cache.get('id1')).toBeUndefined();164        expect(cache.get('id2')).toBe(2);165      }));166      it('should purge the next entry if the stalest one was removed', inject(function($cacheFactory) {167        cache.remove('id0');168        cache.put('id2', 2);169        cache.put('id3', 3);170        expect(cache.get('id0')).toBeUndefined();171        expect(cache.get('id1')).toBeUndefined();172        expect(cache.get('id2')).toBe(2);173        expect(cache.get('id3')).toBe(3);174      }));175      it('should correctly recreate the linked list if all cache entries were removed', inject(function($cacheFactory) {176        cache.remove('id0');177        cache.remove('id1');178        cache.put('id2', 2);179        cache.put('id3', 3);180        cache.put('id4', 4);181        expect(cache.get('id0')).toBeUndefined();182        expect(cache.get('id1')).toBeUndefined();183        expect(cache.get('id2')).toBeUndefined();184        expect(cache.get('id3')).toBe(3);185        expect(cache.get('id4')).toBe(4);186      }));187      it('should blow away the entire cache via removeAll and start evicting when full', inject(function($cacheFactory) {188        cache.put('id0', 0);189        cache.put('id1', 1);190        cache.removeAll();191        cache.put('id2', 2);192        cache.put('id3', 3);193        cache.put('id4', 4);194        expect(cache.info().size).toBe(2);195        expect(cache.get('id0')).toBeUndefined();196        expect(cache.get('id1')).toBeUndefined();197        expect(cache.get('id2')).toBeUndefined();198        expect(cache.get('id3')).toBe(3);199        expect(cache.get('id4')).toBe(4);200      }));201      it('should correctly refresh and evict items if operations are chained', inject(function($cacheFactory) {202        cache = $cacheFactory('cache2', {capacity: 3});203        cache.put('id0', 0); //0204        cache.put('id1', 1); //1,0205        cache.put('id2', 2); //2,1,0206        cache.get('id0');    //0,2,1207        cache.put('id3', 3); //3,0,2208        cache.put('id0', 9); //0,3,2209        cache.put('id4', 4); //4,0,3210        expect(cache.get('id3')).toBe(3);211        expect(cache.get('id0')).toBe(9);212        expect(cache.get('id4')).toBe(4);213        cache.remove('id0'); //4,3214        cache.remove('id3'); //4215        cache.put('id5', 5); //5,4216        cache.put('id6', 6); //6,5,4217        cache.get('id4');    //4,6,5218        cache.put('id7', 7); //7,4,6219        expect(cache.get('id0')).toBeUndefined();220        expect(cache.get('id1')).toBeUndefined();221        expect(cache.get('id2')).toBeUndefined();222        expect(cache.get('id3')).toBeUndefined();223        expect(cache.get('id4')).toBe(4);224        expect(cache.get('id5')).toBeUndefined();225        expect(cache.get('id6')).toBe(6);226        expect(cache.get('id7')).toBe(7);227        cache.removeAll();228        cache.put('id0', 0); //0229        cache.put('id1', 1); //1,0230        cache.put('id2', 2); //2,1,0231        cache.put('id3', 3); //3,2,1232        expect(cache.info().size).toBe(3);233        expect(cache.get('id0')).toBeUndefined();234        expect(cache.get('id1')).toBe(1);235        expect(cache.get('id2')).toBe(2);236        expect(cache.get('id3')).toBe(3);237      }));238    });239  });...

Full Screen

Full Screen

LruCache.js

Source:LruCache.js Github

copy

Full Screen

1describe("Ext.util.LruCache", function(){2    var cache,3        obj1  = {objIdx:1},4        obj2  = {objIdx:2},5        obj3  = {objIdx:3},6        obj4  = {objIdx:4},7        obj5  = {objIdx:5},8        obj6  = {objIdx:6},9        obj7  = {objIdx:7},10        obj8  = {objIdx:8},11        obj9  = {objIdx:9},12        obj10 = {objIdx:10};13    function createCache(config) {14        cache = new Ext.util.LruCache(config);15    }16    describe("Adding", function(){17        it("should create an empty cache", function(){18            createCache();19            expect(cache.length).toBe(0);20            expect(cache.first).toBeNull;21            expect(cache.last).toBeNull();22            expect(cache.getValues()).toEqual([]);23            expect(cache.getKeys()).toEqual([]);24        });25        it("should contain 1 entry", function(){26            createCache();27            cache.add(1, obj1);28            expect(cache.length).toEqual(1);29            expect(cache.first.value).toBe(obj1);30            expect(cache.last.value).toBe(obj1);31            expect(cache.getValues()).toEqual([obj1]);32            expect(cache.getKeys()).toEqual([1]);33        });34        it("should contain 2 entries", function(){35            createCache();36            cache.add(1, obj1);37            cache.add(2, obj2);38            expect(cache.length).toEqual(2);39            expect(cache.first.value).toBe(obj1);40            expect(cache.last.value).toBe(obj2);41            expect(cache.getValues()).toEqual([obj1, obj2]);42            expect(cache.getKeys()).toEqual([1, 2]);43        });44        it("should be able to add existing keys", function() {45            createCache();46            cache.add(1, obj1);47            cache.add(2, obj2);48            cache.add(1, obj3);49            expect(cache.length).toEqual(2);50            expect(cache.first.value).toBe(obj2);51            expect(cache.last.value).toBe(obj3);52            expect(cache.getValues()).toEqual([obj2, obj3]);53            expect(cache.getKeys()).toEqual([2, 1]);54        });55    });56    describe("Sort on access", function() {57        it("should move accessed items to the end", function(){58            createCache();59            cache.add(1, obj1);60            cache.add(2, obj2);61            expect(cache.getValues()).toEqual([obj1, obj2]);62            expect(cache.getKeys()).toEqual([1, 2]);63            cache.get(1);64            expect(cache.getValues()).toEqual([obj2, obj1]);65            expect(cache.getKeys()).toEqual([2, 1]);66        });67    });68    describe("Inserting", function() {69        it("should insert at the requested point", function(){70            createCache();71            cache.add(1, obj1);72            cache.insertBefore(2, obj2, obj1);73            expect(cache.getValues()).toEqual([obj2, obj1]);74            expect(cache.getKeys()).toEqual([2, 1]);75        });76    });77    describe("Iterating", function() {78        it("should iterate in order", function(){79            var result = [];80            createCache();81            cache.add(1, obj1);82            cache.add(2, obj2);83            cache.each(function(key, value, length) {84                result.push(key, value);85            });86            expect(result).toEqual([1, obj1, 2, obj2]);87        });88        it("should iterate in reverse order", function(){89            var result = [];90            createCache();91            cache.add(1, obj1);92            cache.add(2, obj2);93            cache.each(function(key, value, length) {94                result.push(key, value);95            }, null, true);96            expect(result).toEqual([2, obj2, 1, obj1]);97        });98    });99    describe("Removing", function() {100        it("should remove by key and re-link", function(){101            createCache();102            cache.add(1, obj1);103            cache.add(2, obj2);104            cache.add(3, obj3);105            cache.removeAtKey(2)106            expect(cache.getValues()).toEqual([obj1, obj3]);107            expect(cache.getKeys()).toEqual([1, 3]);108        });109        it("should remove by value and re-link", function(){110            createCache();111            cache.add(1, obj1);112            cache.add(2, obj2);113            cache.add(3, obj3);114            cache.remove(obj2)115            expect(cache.getValues()).toEqual([obj1, obj3]);116            expect(cache.getKeys()).toEqual([1, 3]);117        });118    });119    describe("Clearing", function() {120        it("should remove all", function(){121            createCache();122            cache.add(1, obj1);123            cache.add(2, obj2);124            cache.clear();125            expect(cache.getValues()).toEqual([]);126            expect(cache.getKeys()).toEqual([]);127        });128    });129    describe("Purging", function() {130        it("should only contain the last 5 added", function(){131            createCache({132                maxSize: 5133            });134            cache.add(1, obj1);135            cache.add(2, obj2);136            cache.add(3, obj3);137            cache.add(4, obj4);138            cache.add(5, obj5);139            expect(cache.getValues()).toEqual([obj1, obj2, obj3, obj4, obj5]);140            expect(cache.getKeys()).toEqual([1, 2, 3, 4, 5]);141            cache.add(6, obj6);142            expect(cache.getValues()).toEqual([obj2, obj3, obj4, obj5, obj6]);143            expect(cache.getKeys()).toEqual([2, 3, 4, 5, 6]);144            cache.add(7, obj7);145            expect(cache.getValues()).toEqual([obj3, obj4, obj5, obj6, obj7]);146            expect(cache.getKeys()).toEqual([3, 4, 5, 6, 7]);147            cache.add(8, obj8);148            expect(cache.getValues()).toEqual([obj4, obj5, obj6, obj7, obj8]);149            expect(cache.getKeys()).toEqual([4, 5, 6, 7, 8]);150            cache.add(9, obj9);151            expect(cache.getValues()).toEqual([obj5, obj6, obj7, obj8, obj9]);152            expect(cache.getKeys()).toEqual([5, 6, 7, 8, 9]);153            cache.add(10, obj10);154            expect(cache.getValues()).toEqual([obj6, obj7, obj8, obj9, obj10]);155            expect(cache.getKeys()).toEqual([6, 7, 8, 9, 10]);156        });157    });...

Full Screen

Full Screen

cache-plugin-coverage.js

Source:cache-plugin-coverage.js Github

copy

Full Screen

1/*2YUI 3.7.3 (build 5687)3Copyright 2012 Yahoo! Inc. All rights reserved.4Licensed under the BSD License.5http://yuilibrary.com/license/6*/7if (typeof _yuitest_coverage == "undefined"){8    _yuitest_coverage = {};9    _yuitest_coverline = function(src, line){10        var coverage = _yuitest_coverage[src];11        if (!coverage.lines[line]){12            coverage.calledLines++;13        }14        coverage.lines[line]++;15    };16    _yuitest_coverfunc = function(src, name, line){17        var coverage = _yuitest_coverage[src],18            funcId = name + ":" + line;19        if (!coverage.functions[funcId]){20            coverage.calledFunctions++;21        }22        coverage.functions[funcId]++;23    };24}25_yuitest_coverage["build/cache-plugin/cache-plugin.js"] = {26    lines: {},27    functions: {},28    coveredLines: 0,29    calledLines: 0,30    coveredFunctions: 0,31    calledFunctions: 0,32    path: "build/cache-plugin/cache-plugin.js",33    code: []34};35_yuitest_coverage["build/cache-plugin/cache-plugin.js"].code=["YUI.add('cache-plugin', function (Y, NAME) {","","/**"," * Provides support to use Cache as a Plugin to a Base-based class."," *"," * @module cache"," * @submodule cache-plugin"," */","","/**"," * Plugin.Cache adds pluginizability to Cache."," * @class Plugin.Cache"," * @extends Cache"," * @uses Plugin.Base"," */","function CachePlugin(config) {","    var cache = config && config.cache ? config.cache : Y.Cache,","        tmpclass = Y.Base.create(\"dataSourceCache\", cache, [Y.Plugin.Base]),","        tmpinstance = new tmpclass(config);","    tmpclass.NS = \"tmpClass\";","    return tmpinstance;","}","","Y.mix(CachePlugin, {","    /**","     * The namespace for the plugin. This will be the property on the host which","     * references the plugin instance.","     *","     * @property NS","     * @type String","     * @static","     * @final","     * @value \"cache\"","     */","    NS: \"cache\",","","    /**","     * Class name.","     *","     * @property NAME","     * @type String","     * @static","     * @final","     * @value \"dataSourceCache\"","     */","    NAME: \"cachePlugin\"","});","","","Y.namespace(\"Plugin\").Cache = CachePlugin;","","","}, '3.7.3', {\"requires\": [\"plugin\", \"cache-base\"]});"];36_yuitest_coverage["build/cache-plugin/cache-plugin.js"].lines = {"1":0,"16":0,"17":0,"20":0,"21":0,"24":0,"50":0};37_yuitest_coverage["build/cache-plugin/cache-plugin.js"].functions = {"CachePlugin:16":0,"(anonymous 1):1":0};38_yuitest_coverage["build/cache-plugin/cache-plugin.js"].coveredLines = 7;39_yuitest_coverage["build/cache-plugin/cache-plugin.js"].coveredFunctions = 2;40_yuitest_coverline("build/cache-plugin/cache-plugin.js", 1);41YUI.add('cache-plugin', function (Y, NAME) {42/**43 * Provides support to use Cache as a Plugin to a Base-based class.44 *45 * @module cache46 * @submodule cache-plugin47 */48/**49 * Plugin.Cache adds pluginizability to Cache.50 * @class Plugin.Cache51 * @extends Cache52 * @uses Plugin.Base53 */54_yuitest_coverfunc("build/cache-plugin/cache-plugin.js", "(anonymous 1)", 1);55_yuitest_coverline("build/cache-plugin/cache-plugin.js", 16);56function CachePlugin(config) {57    _yuitest_coverfunc("build/cache-plugin/cache-plugin.js", "CachePlugin", 16);58_yuitest_coverline("build/cache-plugin/cache-plugin.js", 17);59var cache = config && config.cache ? config.cache : Y.Cache,60        tmpclass = Y.Base.create("dataSourceCache", cache, [Y.Plugin.Base]),61        tmpinstance = new tmpclass(config);62    _yuitest_coverline("build/cache-plugin/cache-plugin.js", 20);63tmpclass.NS = "tmpClass";64    _yuitest_coverline("build/cache-plugin/cache-plugin.js", 21);65return tmpinstance;66}67_yuitest_coverline("build/cache-plugin/cache-plugin.js", 24);68Y.mix(CachePlugin, {69    /**70     * The namespace for the plugin. This will be the property on the host which71     * references the plugin instance.72     *73     * @property NS74     * @type String75     * @static76     * @final77     * @value "cache"78     */79    NS: "cache",80    /**81     * Class name.82     *83     * @property NAME84     * @type String85     * @static86     * @final87     * @value "dataSourceCache"88     */89    NAME: "cachePlugin"90});91_yuitest_coverline("build/cache-plugin/cache-plugin.js", 50);92Y.namespace("Plugin").Cache = CachePlugin;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Caching API response', function() {2    it('Caching API response', function() {3            .as('todo')4            .its('body')5            .should('have.property', 'userId', 1)6        cy.get('@todo')7            .its('body')8            .should('have.property', 'id', 1)9        cy.get('@todo')10            .its('body')11            .should('have.property', 'title', 'delectus aut autem')12    })13})

Full Screen

Using AI Code Generation

copy

Full Screen

1const cache = require('cypress-cache-api');2const { response } = require('express');3describe('test', () => {4  it('test', () => {5      req.reply((res) => {6        res.body = cache.get('repos');7      });8    });9  });10});11{12  "scripts": {13  },14  "devDependencies": {15  }16}17const express = require('express');18const app = express();19const port = 3000;20const axios = require('axios');21const cache = require('cypress-cache-api');22app.get('/', (req, res) => {23    .then((response) => {24      cache.set('repos', response.data);25      res.send(response.data);26    })27    .catch((err) => console.error(err));28});

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful