How to use getLockFilename method in Cypress

Best JavaScript code snippet using cypress

storage.js

Source:storage.js Github

copy

Full Screen

1/*2 * The MIT License3 *4 * Copyright (c) 2016 Juan Cruz Viotti. https://github.com/jviotti5 *6 * Permission is hereby granted, free of charge, to any person obtaining a copy7 * of this software and associated documentation files (the "Software"), to deal8 * in the Software without restriction, including without limitation the rights9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10 * copies of the Software, and to permit persons to whom the Software is11 * furnished to do so, subject to the following conditions:12 *13 * The above copyright notice and this permission notice shall be included in14 * all copies or substantial portions of the Software.15 *16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22 * THE SOFTWARE.23 */24'use strict';25/**26 * @module storage27 */28const _ = require('lodash');29const async = require('async');30const fs = require('fs');31const rimraf = require('rimraf');32const mkdirp = require('mkdirp');33const path = require('path');34const writeFileAtomic = require('write-file-atomic');35const utils = require('./utils');36const lock = require('./lock');37const readFile = function(fileName, callback, times) {38 times = times || 0;39 fs.readFile(fileName, function(error, object) {40 if (!error) {41 return callback(null, object);42 }43 if (error.code === 'ENOENT') {44 return callback(null, JSON.stringify({}));45 }46 if (error.code === 'EPERM' && times < 10) {47 setTimeout(function() {48 readFile(fileName, callback, times + 1);49 }, 1000);50 return;51 }52 return callback(error);53 });54};55const readFileSync = function(fileName, times) {56 times = times || 0;57 try {58 return fs.readFileSync(fileName);59 } catch (error) {60 if (error.code === 'ENOENT') {61 return JSON.stringify({});62 }63 if (error.code === 'EPERM' && times < 10) {64 return readFileSync(fileName, times + 1);65 }66 throw error;67 }68};69/**70 * @summary Get the default data path71 * @function72 * @public73 *74 * @description75 * This function will return `null` when running in the76 * renderer process without support for the `remote` IPC77 * mechanism. You have to explicitly set a data path using78 * `.setDataPath()` in these cases.79 *80 * @returns {(String|Null)} default data path81 *82 * @example83 * const defaultDataPath = storage.getDefaultDataPath()84 */85exports.getDefaultDataPath = utils.getDefaultDataPath;86/**87 * @summary Set current data path88 * @function89 * @public90 *91 * @description92 * The default value will be used if the directory is undefined.93 *94 * @param {(String|Undefined)} directory - directory95 *96 * @example97 * const os = require('os');98 * const storage = require('electron-json-storage');99 *100 * storage.setDataPath(os.tmpdir());101 */102exports.setDataPath = utils.setDataPath;103/**104 * @summary Get current user data path105 * @function106 * @public107 *108 * @description109 * Returns the current data path. It defaults to a directory called110 * "storage" inside Electron's `userData` path.111 *112 * @returns {String} the user data path113 *114 * @example115 * const storage = require('electron-json-storage');116 *117 * const dataPath = storage.getDataPath();118 * console.log(dataPath);119 */120exports.getDataPath = utils.getDataPath;121/**122 * @summary Read user data123 * @function124 * @public125 *126 * @description127 * If the key doesn't exist in the user data, an empty object is returned.128 * Also notice that the `.json` extension is added automatically, but it's129 * ignored if you pass it yourself.130 *131 * Passing an extension other than `.json` will result in a file created132 * with both extensions. For example, the key `foo.data` will result in a file133 * called `foo.data.json`.134 *135 * @param {String} key - key136 * @param {Object} [options] - options137 * @param {String} [options.dataPath] - data path138 * @param {Function} callback - callback (error, data)139 *140 * @example141 * const storage = require('electron-json-storage');142 *143 * storage.get('foobar', function(error, data) {144 * if (error) throw error;145 *146 * console.log(data);147 * });148 */149exports.get = function(key, options, callback) {150 if (_.isFunction(options)) {151 callback = options;152 }153 options = options || {};154 callback = callback || _.noop;155 var fileName = null;156 async.waterfall([157 async.asyncify(_.partial(utils.getFileName, key, {158 dataPath: options.dataPath159 })),160 function(result, callback) {161 fileName = result;162 mkdirp(path.dirname(fileName), callback);163 },164 function(made, next) {165 lock.lock(utils.getLockFileName(fileName), function(error) {166 if (error && error.code === 'EEXIST') {167 return exports.get(key, options, callback);168 }169 return next(error);170 });171 },172 function(callback) {173 readFile(fileName, callback);174 },175 function(object, callback) {176 var objectJSON = {};177 try {178 objectJSON = JSON.parse(object);179 } catch (error) {180 return callback(new Error('Invalid data: ' + object));181 }182 return callback(null, objectJSON);183 }184 ], function(error, result) {185 lock.unlock(utils.getLockFileName(fileName), function(lockError) {186 if (error) {187 return callback(error);188 }189 return callback(lockError, result);190 });191 });192};193/**194 * @summary Read user data (sync)195 * @function196 * @public197 *198 * @description199 * See `.get()`.200 *201 * @param {String} key - key202 * @param {Object} [options] - options203 * @param {String} [options.dataPath] - data path204 *205 * @example206 * const storage = require('electron-json-storage');207 *208 * var data = storage.getSync('foobar');209 * console.log(data);210 */211exports.getSync = function(key, options) {212 options = options || {};213 var fileName = utils.getFileName(key, {214 dataPath: options.dataPath215 });216 mkdirp.sync(path.dirname(fileName));217 try {218 lock.lockSync(utils.getLockFileName(fileName));219 } catch (error) {220 if (error && error.code === 'EEXIST') {221 return exports.getSync(key, options);222 }223 throw error;224 }225 var object = readFileSync(fileName);226 lock.unlockSync(utils.getLockFileName(fileName));227 try {228 return JSON.parse(object);229 } catch (error) {230 throw new Error('Invalid data: ' + object);231 }232};233/**234 * @summary Read many user data keys235 * @function236 * @public237 *238 * @description239 * This function returns an object with the data of all the passed keys.240 * If one of the keys doesn't exist, an empty object is returned for it.241 *242 * @param {String[]} keys - keys243 * @param {Object} [options] - options244 * @param {String} [options.dataPath] - data path245 * @param {Function} callback - callback (error, data)246 *247 * @example248 * const storage = require('electron-json-storage');249 *250 * storage.getMany([ 'foobar', 'barbaz' ], function(error, data) {251 * if (error) throw error;252 *253 * console.log(data.foobar);254 * console.log(data.barbaz);255 * });256 */257exports.getMany = function(keys, options, callback) {258 if (_.isFunction(options)) {259 callback = options;260 options = {};261 }262 options = options || {};263 callback = callback || _.noop;264 async.reduce(keys, {}, function(reducer, key, callback) {265 exports.get(key, options, function(error, data) {266 if (error) {267 return callback(error);268 }269 return callback(null, _.set(reducer, key, data));270 });271 }, callback);272};273/**274 * @summary Read all user data275 * @function276 * @public277 *278 * @description279 * This function returns an empty object if there is no data to be read.280 *281 * @param {Object} [options] - options282 * @param {String} [options.dataPath] - data path283 * @param {Function} callback - callback (error, data)284 *285 * @example286 * const storage = require('electron-json-storage');287 *288 * storage.getAll(function(error, data) {289 * if (error) throw error;290 *291 * console.log(data);292 * });293 */294exports.getAll = function(options, callback) {295 if (_.isFunction(options)) {296 callback = options;297 options = {};298 }299 options = options || {};300 callback = callback || _.noop;301 async.waterfall([302 _.partial(exports.keys, options),303 function(keys, callback) {304 async.reduce(keys, {}, function(reducer, key, callback) {305 async.waterfall([306 _.partial(exports.get, key, options),307 function(contents, callback) {308 return callback(null, _.set(reducer, key, contents));309 }310 ], callback);311 }, callback);312 }313 ], callback);314};315/**316 * @summary Write user data317 * @function318 * @public319 *320 * @param {String} key - key321 * @param {Object} json - json object322 * @param {Object} [options] - options323 * @param {String} [options.dataPath] - data path324 * @param {String} [options.validate] - validate writes by reading the data back325 * @param {boolean} [options.prettyPrinting] - adds line breaks and spacing to the written data326 * @param {Function} callback - callback (error)327 *328 * @example329 * const storage = require('electron-json-storage');330 *331 * storage.set('foobar', { foo: 'bar' }, function(error) {332 * if (error) throw error;333 * });334 */335exports.set = function(key, json, options, callback, retries) {336 if (!_.isNumber(retries)) {337 retries = 10;338 }339 if (_.isFunction(options)) {340 callback = options;341 }342 options = options || {};343 callback = callback || _.noop;344 var fileName = null;345 async.waterfall([346 async.asyncify(_.partial(utils.getFileName, key, {347 dataPath: options.dataPath348 })),349 function(result, callback) {350 fileName = result;351 const data = JSON.stringify(json, null, (options.prettyPrinting ? 2 : 0));352 if (!data) {353 return callback(new Error('Invalid JSON data'));354 }355 // Create the directory in case it doesn't exist yet356 mkdirp(path.dirname(fileName), function(error) {357 return callback(error, data);358 });359 },360 function(data, next) {361 lock.lock(utils.getLockFileName(fileName), function(error) {362 if (error && error.code === 'EEXIST') {363 return exports.set(key, json, options, callback);364 }365 return next(error, fileName, data);366 });367 },368 function(fileName, data, callback) {369 writeFileAtomic(fileName, data, callback);370 }371 ], function(error) {372 lock.unlock(utils.getLockFileName(fileName), function(lockError) {373 if (error) {374 return callback(error);375 }376 if (!options.validate) {377 return callback(lockError);378 }379 // Check that the writes were actually successful380 // after a little bit381 setTimeout(function() {382 exports.get(key, {383 dataPath: options.dataPath384 }, function(getError, data) {385 if (getError) {386 return callback(getError);387 }388 if (!_.isEqual(data, json)) {389 if (retries <= 0) {390 throw new Error('Couldn\'t ensure data was written correctly');391 }392 return exports.set(key, json, options, callback, retries - 1);393 }394 return callback();395 });396 }, 100);397 });398 });399};400/**401 * @summary Check if a key exists402 * @function403 * @public404 *405 * @param {String} key - key406 * @param {Object} [options] - options407 * @param {String} [options.dataPath] - data path408 * @param {Function} callback - callback (error, hasKey)409 *410 * @example411 * const storage = require('electron-json-storage');412 *413 * storage.has('foobar', function(error, hasKey) {414 * if (error) throw error;415 *416 * if (hasKey) {417 * console.log('There is data stored as `foobar`');418 * }419 * });420 */421exports.has = function(key, options, callback) {422 if (_.isFunction(options)) {423 callback = options;424 }425 options = options || {};426 callback = callback || _.noop;427 async.waterfall([428 async.asyncify(_.partial(utils.getFileName, key, {429 dataPath: options.dataPath430 })),431 function(filename, done) {432 fs.stat(filename, function(error) {433 if (error) {434 if (error.code === 'ENOENT') {435 return done(null, false);436 }437 return done(error);438 }439 return done(null, true);440 });441 }442 ], callback);443};444/**445 * @summary Get the list of saved keys446 * @function447 * @public448 *449 * @param {Object} [options] - options450 * @param {String} [options.dataPath] - data path451 * @param {Function} callback - callback (error, keys)452 *453 * @example454 * const storage = require('electron-json-storage');455 *456 * storage.keys(function(error, keys) {457 * if (error) throw error;458 *459 * for (var key of keys) {460 * console.log('There is a key called: ' + key);461 * }462 * });463 */464exports.keys = function(options, callback) {465 if (_.isFunction(options)) {466 callback = options;467 options = {};468 }469 options = options || {};470 callback = callback || _.noop;471 async.waterfall([472 function(callback) {473 callback(null, options.dataPath || exports.getDataPath());474 },475 function(userDataPath, callback) {476 mkdirp(userDataPath, function(error) {477 return callback(error, userDataPath);478 });479 },480 fs.readdir,481 function(keys, callback) {482 callback(null, _.map(_.reject(keys, function(key) {483 return path.extname(key) !== '.json';484 }), function(key) {485 return path.basename(decodeURIComponent(key), '.json');486 }));487 }488 ], callback);489};490/**491 * @summary Remove a key492 * @function493 * @public494 *495 * @description496 * Notice this function does nothing, nor throws any error497 * if the key doesn't exist.498 *499 * @param {String} key - key500 * @param {Object} [options] - options501 * @param {String} [options.dataPath] - data path502 * @param {Function} callback - callback (error)503 *504 * @example505 * const storage = require('electron-json-storage');506 *507 * storage.remove('foobar', function(error) {508 * if (error) throw error;509 * });510 */511exports.remove = function(key, options, callback) {512 if (_.isFunction(options)) {513 callback = options;514 }515 options = options || {};516 callback = callback || _.noop;517 async.waterfall([518 async.asyncify(_.partial(utils.getFileName, key, {519 dataPath: options.dataPath520 })),521 rimraf522 ], callback);523};524/**525 * @summary Clear all stored data in the current user data path526 * @function527 * @public528 *529 * @param {Object} [options] - options530 * @param {String} [options.dataPath] - data path531 * @param {Function} callback - callback (error)532 *533 * @example534 * const storage = require('electron-json-storage');535 *536 * storage.clear(function(error) {537 * if (error) throw error;538 * });539 */540exports.clear = function(options, callback) {541 if (_.isFunction(options)) {542 callback = options;543 }544 options = options || {};545 callback = callback || _.noop;546 const userData = options.dataPath || exports.getDataPath();547 const jsonFiles = path.join(userData, '*.json');548 rimraf(jsonFiles, callback);...

Full Screen

Full Screen

database.js

Source:database.js Github

copy

Full Screen

1var fs = require('fs');2var path = require('path');3var util = require('util');4var events = require('events');5var log = require('./default_log.js').log;6var TimeEntry = require('./time_entry.js');7var Group = require('./group.js');8var HashSet = require('./hashset.js').HashSet;9var log = require('./default_log.js').log;10/* Error codes. Make sure that these do not overlap with the error codes in time_entry.js! */11exports.ERR_NOT_FOUND = 10;12const NORMAL = 0,13 LOCKING = 1,14 LOCKED = 2;15const MAX_UNEVICTED = 1024 * 1024 * 64;16const SYNC_AND_EVICT_INTERVAL = 10000;17function Database(dbpath) {18 events.EventEmitter.call(this);19 this.dbpath = dbpath;20 this.groupCount = 0;21 this.groups = {};22 this.lastObjectId = 0;23 24 this.state = NORMAL;25 this.addOperations = 0;26 this.waitingLockers = [];27 this.waitingAddOperations = [];28 this.syncAndEvictInProgress = false;29 30 this.unevictedSize = 0;31 this.unevictedTimeEntries = new HashSet();32}33util.inherits(Database, events.EventEmitter);34function createError(message, code) {35 var e = new Error(message);36 e.code = code;37 e.codeno = exports[code];38 console.assert(e.codeno != undefined);39 return e;40}41Database.prototype._verifyInvariants = function() {42 console.assert(this.waitingLockers.length >= 0);43 console.assert(this.waitingAddOperations.length >= 0);44 console.assert(this.unevictedSize >= 0);45 console.assert(!( this.state == NORMAL ) || ( this.waitingLockers.length == 0 ));46 console.assert(!( this.state == NORMAL ) || ( this.waitingAddOperations.length == 0 ));47 console.assert(!( this.state == LOCKING ) || ( this.waitingLockers.length > 0 ));48}49Database.prototype._checkClean = function() {50 var stat;51 try {52 stat = fs.statSync(this.getLockFileName());53 return false;54 } catch (e) {55 if (e.code == 'ENOENT') {56 return true;57 } else {58 throw e;59 }60 }61}62Database.prototype.getLockFileName = function() {63 return this.dbpath + '/lock';64}65Database.prototype.start = function() {66 console.assert(this.flushTimerId === undefined);67 this.clean = this._checkClean();68 this.syncAndEvictTimerId = setInterval(this.syncAndEvict.bind(this),69 SYNC_AND_EVICT_INTERVAL);70 var fd = fs.openSync(this.getLockFileName(), 'w', 0644);71 fs.fsyncSync(fd);72 fs.closeSync(fd);73}74Database.prototype.close = function() {75 var groupName;76 clearInterval(this.syncAndEvictTimerId);77 delete this.syncAndEvictTimerId;78 for (groupName in this.groups) {79 this.groups[groupName].close();80 }81 this.groupCount = 0;82 this.groups = {};83 this.unevictedSize = 0;84 this.unevictedTimeEntries.clear();85 fs.unlinkSync(this.getLockFileName());86}87Database.prototype.reload = function() {88 // TODO: clear stale renames upon reloading89 90 var groupDirs = fs.readdirSync(this.dbpath);91 var i, groupName, groupPath, stats, timeEntryDirs, group,92 j, timePath, dayTimestamp, dataPath, stream, timeEntry;93 var newState = {94 groupCount: 0,95 groups: {},96 lastObjectId: 097 };98 99 for (i = 0; i < groupDirs.length; i++) {100 if (groupDirs[i][0] == '.') {101 continue;102 }103 104 groupName = groupDirs[i];105 groupPath = path.join(this.dbpath, groupDirs[i]);106 stats = fs.statSync(groupPath);107 if (!stats.isDirectory()) {108 continue;109 }110 111 timeEntryDirs = fs.readdirSync(groupPath);112 group = new Group.Group(groupName, groupPath);113 newState.groupCount++;114 newState.groups[groupName] = group;115 116 for (j = 0; j < timeEntryDirs.length; j++) {117 if (timeEntryDirs[j][0] == '.' || !looksLikeTimestamp(timeEntryDirs[j])) {118 continue;119 }120 121 timePath = path.join(groupPath, timeEntryDirs[j]);122 stats = fs.statSync(timePath);123 if (!stats.isDirectory()) {124 continue;125 }126 127 dayTimestamp = parseInt(timeEntryDirs[j]);128 dataPath = path.join(timePath, "data");129 try {130 stats = fs.statSync(dataPath);131 } catch (err) {132 if (err.code == 'ENOENT') {133 try {134 stream = openDataFile(dataPath);135 } catch (err) {136 throw new Error("Cannot create data file " +137 dataPath + ": " + err);138 }139 timeEntry = new TimeEntry.TimeEntry(this,140 newState.lastObjectId, dayTimestamp,141 timePath, stream, 0);142 newState.lastObjectId++;143 group.timeEntryCount++;144 group.timeEntries[dayTimestamp] = timeEntry;145 } else {146 throw new Error("Cannot stat data file " +147 dataPath + ": " + err.message);148 }149 continue;150 }151 152 if (!stats.isFile()) {153 throw new Error("Data file " + dataPath + " is not a file");154 }155 try {156 stream = openDataFile(dataPath);157 } catch (err) {158 throw new Error("Cannot create data file " +159 dataPath + ": " + err);160 }161 timeEntry = new TimeEntry.TimeEntry(this, newState.lastObjectId,162 dayTimestamp, timePath, stream, stats.size);163 newState.lastObjectId++;164 group.timeEntryCount++;165 group.timeEntries[dayTimestamp] = timeEntry;166 }167 }168 169 var groupName;170 for (groupName in this.groups) {171 this.groups[groupName].close();172 }173 this.groupCount = newState.groupCount;174 this.groups = newState.groups;175 this.lastObjectId = newState.lastObjectId;176 this.unflushedSize = 0;177}178Database.prototype._findOrCreateGroup = function(groupName) {179 if (!Group.validateGroupName(groupName)) {180 throw new Error('Invalid group name');181 }182 183 var group = this.groups[groupName];184 if (!group) {185 var groupPath = path.join(this.dbpath, groupName);186 try {187 fs.mkdirSync(groupPath, 0755);188 } catch (err) {189 if (err.code != 'EEXIST') {190 throw err;191 }192 }193 group = new Group.Group(groupName, groupPath);194 this.groups[groupName] = group;195 }196 return group;197}198Database.prototype._findOrCreateTimeEntry = function(groupName, dayTimestamp) {199 var group = this._findOrCreateGroup(groupName);200 var timeEntry = group.timeEntries[dayTimestamp];201 if (!timeEntry) {202 var timePath = path.join(this.dbpath, groupName, dayTimestamp + "");203 var dataPath = path.join(timePath, "data");204 var size;205 206 try {207 fs.mkdirSync(timePath, 0700);208 size = 0;209 } catch (err) {210 if (err.code == 'EEXIST') {211 try {212 size = fs.statSync(dataPath).size;213 } catch (err) {214 if (err.code == 'ENOENT') {215 size = 0;216 } else {217 throw err;218 }219 }220 } else {221 throw err;222 }223 }224 225 var stream = openDataFile(dataPath);226 group.timeEntryCount++;227 timeEntry = new TimeEntry.TimeEntry(this, this.lastObjectId,228 dayTimestamp, timePath, stream, size);229 this.lastObjectId++;230 group.timeEntries[dayTimestamp] = timeEntry;231 }232 return timeEntry;233}234Database.prototype.findTimeEntry = function(groupName, dayTimestamp) {235 var group = this.groups[groupName];236 if (group) {237 return group.timeEntries[dayTimestamp];238 }239}240Database.prototype.get = function(groupName, dayTimestamp, offset, callback) {241 var timeEntry = this.findTimeEntry(groupName, dayTimestamp);242 if (timeEntry) {243 return timeEntry.get(offset, callback);244 } else {245 callback(createError('Time entry not found', 'ERR_NOT_FOUND'));246 }247}248Database.prototype.add = function(opid, groupName, dayTimestamp, buffers, checksumBuffer, options, callback) {249 var timeEntry;250 if (typeof(options) == 'function') {251 callback = options;252 options = undefined;253 }254 try {255 timeEntry = this._findOrCreateTimeEntry(groupName, dayTimestamp);256 } catch (err) {257 callback(err);258 return;259 }260 /*261 * Perform two concurrent operations:262 * 1. Emit 'adding' and wait until all listeners263 * have reported that they're done.264 * 2. Store the data on local disk and wait until265 * it's done.266 *267 * The callback is called after both operations are done.268 */269 270 var self = this;271 var concurrentOperationsDone = 0;272 var result;273 function callAddingListeners() {274 var listeners = self.listeners('adding').length;275 if (listeners > 0) {276 var counter = 0;277 self.emit('adding', timeEntry, groupName, dayTimestamp, buffers, function() {278 console.assert(counter <= listeners);279 counter++;280 if (counter == listeners) {281 concurrentOperationDone();282 }283 });284 } else {285 concurrentOperationDone();286 }287 }288 function storeOnLocalDisk(callback) {289 if (self.state == LOCKING || self.state == LOCKED) {290 self.waitingAddOperations.push(performStoringOnLocalDisk);291 } else {292 performStoringOnLocalDisk();293 }294 }295 function concurrentOperationDone() {296 console.assert(concurrentOperationsDone <= 2);297 concurrentOperationsDone++;298 if (concurrentOperationsDone == 2) {299 allConcurrentOperationsDone();300 }301 }302 function allConcurrentOperationsDone() {303 var err = result.err;304 var offset = result.offset;305 var size = result.size;306 var buffers = result.buffers;307 308 self.unevictedTimeEntries.add(timeEntry);309 self.unevictedSize += size;310 if (self.unevictedSize >= MAX_UNEVICTED) {311 self.syncAndEvict();312 console.assert(self.state == LOCKING);313 console.assert(self.waitingLockers.length > 0);314 }315 self.addOperations--;316 timeEntry.decWriteOperations();317 timeEntry._verifyInvariants();318 self._verifyInvariants();319 320 if (self.addOperations == 0 && self.state == LOCKING) {321 console.assert(self.waitingLockers.length > 0);322 self.state = LOCKED;323 var cb = self.waitingLockers.shift();324 cb();325 }326 327 if (err) {328 callback(err);329 } else {330 callback(undefined, offset, size);331 }332 }333 334 function reallyAdd() {335 timeEntry.add(buffers, checksumBuffer, options, function(err, offset, size, buffers) {336 console.assert(self.addOperations > 0);337 console.assert(self.state == NORMAL || self.state == LOCKING);338 339 self.emit('added', timeEntry, groupName, dayTimestamp, offset, size, buffers);340 result = {341 err : err,342 offset : offset,343 size : size,344 buffers: buffers345 }346 concurrentOperationDone();347 });348 }349 350 function performStoringOnLocalDisk() {351 console.assert(self.state == NORMAL);352 self.addOperations++;353 if (self.addSleepTime !== undefined) {354 setTimeout(reallyAdd, self.addSleepTime);355 } else {356 reallyAdd();357 }358 }359 timeEntry.incWriteOperations();360 callAddingListeners();361 storeOnLocalDisk();362}363Database.prototype.remove = function(groupName, dayTimestamp, callback) {364 console.assert(Group.validateGroupName(groupName));365 console.assert(dayTimestamp === undefined || looksLikeTimestamp(dayTimestamp));366 367 var group = this.groups[groupName];368 if (!group) {369 callback();370 return;371 }372 373 var self = this;374 if (!dayTimestamp) {375 this.groupCount--;376 delete this.groups[groupName];377 }378 group.remove(dayTimestamp, function(err) {379 if (err) {380 callback(err);381 } else {382 self.emit('remove', groupName, dayTimestamp);383 callback();384 }385 });386}387Database.prototype.removeOne = function(groupName, dayTimestamp, callback) {388 console.assert(Group.validateGroupName(groupName));389 console.assert(looksLikeTimestamp(dayTimestamp));390 391 var group = this.groups[groupName];392 if (!group) {393 callback();394 return;395 }396 397 var self = this;398 group.removeOne(dayTimestamp, function(err) {399 if (err) {400 callback(err);401 } else {402 self.emit('removeOne', groupName, dayTimestamp);403 callback();404 }405 });406}407Database.prototype.syncAndEvict = function() {408 var self = this;409 410 if (this.syncAndEvictInProgress) {411 return;412 }413 this.syncAndEvictInProgress = true;414 this.lock(function() {415 var timeEntries = self.unevictedTimeEntries.values();416 if (timeEntries.length == 0) {417 self.syncAndEvictInProgress = false;418 return self.unlock();419 }420 421 var i;422 var counter = 0;423 var evictingSize = self.unevictedSize;424 425 self.unevictedTimeEntries.clear();426 self.unevictedSize = 0;427 428 function done() {429 self.syncAndEvictInProgress = false;430 log.debug("Done evicting.");431 self.unlock();432 }433 434 function decCounter() {435 console.assert(counter > 0);436 counter--;437 if (counter == 0) {438 done();439 }440 }441 442 function doSyncAndEvict(timeEntry) {443 timeEntry.sync(function(err) {444 if (timeEntry.isClosed() || err) {445 decCounter();446 } else {447 timeEntry.evict(decCounter);448 }449 });450 }451 452 for (i = 0; i < timeEntries.length; i++) {453 if (!timeEntries[i].isClosed()) {454 counter++;455 }456 }457 for (i = 0; i < timeEntries.length; i++) {458 if (!timeEntries[i].isClosed()) {459 doSyncAndEvict(timeEntries[i]);460 }461 }462 463 if (counter == 0) {464 done();465 } else if (evictingSize < 1024 * 1024) {466 log.debug("Evicting %s KB over %d entries...",467 (evictingSize / 1024).toFixed(2),468 timeEntries.length);469 } else {470 log.debug("Evicting %s MB over %d entries...",471 (evictingSize / 1024 / 1024).toFixed(2),472 timeEntries.length);473 }474 });475}476Database.prototype.lock = function(callback) {477 if (this.state == LOCKING || this.state == LOCKED) {478 this.waitingLockers.push(callback);479 } else {480 console.assert(this.state == NORMAL);481 if (this.addOperations > 0) {482 this.state = LOCKING;483 this.waitingLockers.push(callback);484 } else {485 this.state = LOCKED;486 callback();487 }488 }489}490Database.prototype.unlock = function() {491 console.assert(this.state == LOCKED);492 console.assert(this.addOperations == 0);493 var callback = this.waitingLockers.shift();494 if (callback) {495 this._verifyInvariants();496 callback();497 } else {498 this.state = NORMAL;499 var callbacks = this.waitingAddOperations;500 var origLength = callbacks.length;501 this.waitingAddOperations = [];502 while (callbacks.length > 0) {503 callback = callbacks.shift();504 callback();505 }506 console.assert(this.addOperations == origLength);507 console.assert(this.state == NORMAL);508 this._verifyInvariants();509 }510}511Database.prototype.toTocFormat = function() {512 var toc = {};513 var groupName;514 var group, groupInToc;515 var dayTimestamp;516 var timeEntry, timeEntryInToc;517 518 for (groupName in this.groups) {519 group = this.groups[groupName];520 groupInToc = toc[groupName] = {};521 for (dayTimestamp in group.timeEntries) {522 timeEntry = group.timeEntries[dayTimestamp];523 timeEntryInToc = groupInToc[dayTimestamp] = {};524 timeEntryInToc.size = timeEntry.writtenSize;525 }526 }527 528 return toc;529}530Database.prototype.calculateRecordSize = function(buffers) {531 return TimeEntry.calculateRecordSize(buffers);532}533function looksLikeTimestamp(name) {534 return name == parseInt(name) + '';535}536function openDataFile(filename, callback) {537 return fs.createWriteStream(filename, {538 flags: 'a+',539 encoding: null,540 mode: 0600,541 fd: fs.openSync(filename, 'a+', 0600)542 });543}544exports.Database = Database;545exports.MAX_SIZE = TimeEntry.MAX_SIZE;546exports.MAX_SIZE_DESCRIPTION = TimeEntry.MAX_SIZE_DESCRIPTION;547exports.NORMAL = NORMAL;548exports.LOCKING = LOCKING;...

Full Screen

Full Screen

eject.js

Source:eject.js Github

copy

Full Screen

1'use strict';2const fs = require('fs-extra');3const path = require('path');4const spawn = require('cross-spawn');5const inquirer = require('inquirer');6const appPath = (...paths) => path.join(process.cwd(), ...paths);7const ownDependencyNames = [8 'inquirer',9 'cross-spawn',10 'chalk',11 'fs-extra',12 'mkdirp'13];14const usingPnpm = fs.existsSync(appPath('shrinkwrap.yaml'));15const usingYarn = fs.existsSync(appPath('yarn.lock'));16function getDependenciesManagerName() {17 if (usingPnpm) return 'pnpm';18 if (usingYarn) return 'yarn';19 return 'npm';20}21function getLockFileName() {22 switch (getDependenciesManagerName()) {23 case 'yarn':24 return 'yarn.lock';25 case 'pnpm':26 return 'shrinkwrap.yaml';27 default:28 return undefined;29 }30}31function getPromptMessage() {32 const baseMessage =33 'Are you sure you want to eject? This flavor is designed so that you do not have to do so, if I forgot a use case, please open an issue at\n\nhttps://github.com/cyclejs-community/one-fits-all\n\nThis process is NOT reversable, it will remove all traces of the flavor from your project\n';34 if (getDependenciesManagerName() === 'npm') return baseMessage;35 return `${baseMessage}\nYou are using ${getDependenciesManagerName()} which will cause this script to delete your ${getLockFileName()} and node_modules and reinstall afterwards\n`;36}37inquirer38 .prompt([39 {40 type: 'confirm',41 name: 'confirm',42 default: false,43 message: getPromptMessage()44 }45 ])46 .then(answers => {47 if (!answers.confirm) {48 return;49 }50 const ownPackageJsonPath = path.resolve(51 __dirname,52 '..',53 'package.json'54 );55 const appPackageJsonPath = appPath('package.json');56 const ownPackageJson = JSON.parse(fs.readFileSync(ownPackageJsonPath));57 const appPackageJson = JSON.parse(fs.readFileSync(appPackageJsonPath));58 const mochaArgs = appPackageJson['mocha-webpack'].include.join(' ');59 // Declaring new scripts60 const scripts = {61 start:62 'cross-env NODE_ENV=development webpack-dev-server --config configs/webpack.config.js',63 test:64 'cross-env NODE_ENV=test nyc mocha-webpack --colors --webpack-config configs/webpack.config.js ' +65 mochaArgs,66 build:67 'cross-env NODE_ENV=production webpack --config configs/webpack.config.js',68 clean: 'rimraf build .nyc_output coverage'69 };70 // Declare the new dependencies, excluding self71 let devDependencies = {};72 Object.keys(appPackageJson.devDependencies)73 .filter(dep => dep !== ownPackageJson.name)74 .forEach(dep => {75 devDependencies[dep] = appPackageJson.devDependencies[dep];76 });77 devDependencies = Object.assign(78 {},79 devDependencies,80 Object.keys(ownPackageJson.dependencies)81 .filter(dep => ownDependencyNames.indexOf(dep) === -1)82 .reduce(83 (a, c) =>84 Object.assign(a, {85 [c]: ownPackageJson.dependencies[c]86 }),87 {}88 )89 );90 // Write the new package.json91 const newPackageJson = Object.assign({}, appPackageJson, {92 scripts: scripts,93 devDependencies: devDependencies94 });95 delete newPackageJson['mocha-webpack'];96 fs.writeFileSync(97 appPackageJsonPath,98 JSON.stringify(newPackageJson, null, 2)99 );100 fs.mkdirSync(appPath('configs'));101 fs.copySync(102 path.join(__dirname, '..', 'configs', 'webpack.config.js'),103 appPath('configs', 'webpack.config.js')104 );105 // npm is ok about installing new dependencies106 // it seems this is not necessary to remove lock file and node_modules107 if (getDependenciesManagerName() !== 'npm') {108 fs.removeSync(appPath(getLockFileName()));109 fs.removeSync(appPath('node_modules'));110 }111 spawn.sync(getDependenciesManagerName(), ['install'], {112 stdio: 'inherit'113 });...

Full Screen

Full Screen

helpers.js

Source:helpers.js Github

copy

Full Screen

...143 * Build a file path to a lock file in the tmp directory144 *145 * @param {string} filename146 */147function getLockFilename( filename )148{149 const name = path.basename( filename );150 const dirHash = md5( path.dirname( filename ) );151 return path.join( os.tmpdir(), `${dirHash}-${name}.lock` );152}153/**154 * Create a lockfile (async)155 *156 * @param {string} filename157 */158async function lock( filename )159{160 await lfLock(161 getLockFilename( filename ),162 {163 wait: 6000,164 retryWait: 100,165 stale: 5000,166 retries: 100,167 },168 );169}170/**171 * Remove a lockfile (async)172 *173 * @param {string} filename174 */175async function unlock( filename )176{177 await lfUnlock( getLockFilename( filename ) );178}179module.exports = {180 maybeArrayWrap,181 filterHashes,182 getSRIHash,183 warn,184 varType,185 isObject,186 getSortedObject,187 findMapKeysByValue,188 group,189 getLockFilename,190 lock,191 unlock,...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

1/*2 * The MIT License3 *4 * Copyright (c) 2016 Juan Cruz Viotti. https://github.com/jviotti5 *6 * Permission is hereby granted, free of charge, to any person obtaining a copy7 * of this software and associated documentation files (the "Software"), to deal8 * in the Software without restriction, including without limitation the rights9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell10 * copies of the Software, and to permit persons to whom the Software is11 * furnished to do so, subject to the following conditions:12 *13 * The above copyright notice and this permission notice shall be included in14 * all copies or substantial portions of the Software.15 *16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22 * THE SOFTWARE.23 */24'use strict';25const _ = require('lodash');26const path = require('path');27const electron = require('electron');28const app = electron.app || (electron.remote && electron.remote.app) || null;29/**30 * @summary Get the default data path31 * @function32 * @public33 *34 * @returns {String} default data path35 *36 * @example37 * const defaultDataPath = utils.getDefaultDataPath()38 */39exports.getDefaultDataPath = function() {40 if (!app) {41 return null;42 }43 return path.join(app.getPath('userData'), 'storage');44};45/**46 * @summary The current data path47 * @type {String}48 */49var currentDataPath;50/**51 * @summary Set default data path52 * @function53 * @public54 *55 * @param {String} directory - directory56 *57 * @example58 * const os = require('os');59 * utils.setDataPath(os.tmpdir());60 */61exports.setDataPath = function(directory) {62 if (_.isNil(directory)) {63 currentDataPath = undefined;64 return;65 }66 if (!path.isAbsolute(directory)) {67 throw new Error('The user data path should be an absolute directory');68 }69 currentDataPath = path.normalize(directory);70};71/**72 * @summary Get data path73 * @function74 * @public75 *76 * @returns {Strings} data path77 *78 * @example79 * const dataPath = utils.getDataPath();80 * console.log(dataPath);81 */82exports.getDataPath = function() {83 return currentDataPath || exports.getDefaultDataPath();84};85/**86 * @summary Get storage file name for a key87 * @function88 * @public89 *90 * @param {String} key - key91 * @param {Object} [options] - options92 * @param {String} [options.dataPath] - custom data path93 * @returns {String} file name94 *95 * @example96 * let fileName = utils.getFileName('foo');97 * console.log(fileName);98 */99exports.getFileName = function(key, options) {100 options = options || {};101 if (!key) {102 throw new Error('Missing key');103 }104 if (!_.isString(key) || key.trim().length === 0) {105 throw new Error('Invalid key');106 }107 // Trick to prevent adding the `.json` twice108 // if the key already contains it.109 const keyFileName = path.basename(key, '.json') + '.json';110 // Prevent ENOENT and other similar errors when using111 // reserved characters in Windows filenames.112 // See: https://en.wikipedia.org/wiki/Filename#Reserved%5Fcharacters%5Fand%5Fwords113 const escapedFileName = encodeURIComponent(keyFileName)114 .replace(/\*/g, '-').replace(/%20/g, ' ');115 const dataPath = options.dataPath || exports.getDataPath();116 if (!dataPath) {117 throw new Error('You must explicitly set a data path');118 }119 return path.join(dataPath, escapedFileName);120};121/**122 * @summary Get the lock file out of a file name123 * @function124 * @public125 *126 * @param {String} fileName - file name127 * @returns {String} lock file name128 *129 * @example130 * let lockFileName = utils.getLockFileName('foo');131 * console.log(lockFileName);132 */133exports.getLockFileName = function(fileName) {134 return fileName + '.lock';...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...31 execute() {32 return __awaiter(this, void 0, void 0, function* () {33 logger_1.default.debug('Creating diff ...');34 if (yield this.shouldCreateDiff()) {35 logger_1.default.info(this.packageManager.getLockFilename() + ' updated ! Gathering data ...');36 const packageVersionDiffListCreator = new PackageVersionDiffListCreator_1.default(this.packageManager, this.githubFileManager, this.baseCommitSha, this.headCommitSha);37 logger_1.default.debug('Creating diff ...');38 const packagesDiff = yield packageVersionDiffListCreator.createPackageVersionList();39 yield this.manageDiffNotification(packagesDiff);40 return packagesDiff;41 }42 logger_1.default.info(this.packageManager.getLockFilename() + ' not updated on that PR !');43 yield this.githubCommentManager.deletePreviousIfExisting();44 return [];45 });46 }47 manageDiffNotification(packagesDiff) {48 return __awaiter(this, void 0, void 0, function* () {49 if (packagesDiff.length) {50 return this.githubCommentManager.createNewIfNeeded(this.headCommitSha, packagesDiff);51 }52 return this.githubCommentManager.deletePreviousIfExisting();53 });54 }55 shouldCreateDiff() {56 return __awaiter(this, void 0, void 0, function* () {57 // /!\ Checking only between comment commit and latest commit may produce bad result58 // see https://github.com/yoanm/github-action-deps-versions-checker/issues/6359 // ==> Always check between base branch and latest commit instead60 logger_1.default.debug('Checking if lock file has been updated on PR ...');61 const lockFile = yield this.githubFileManager.getPRFile(this.packageManager.getLockFilename(), this.prId, ['modified', 'added', 'removed']);62 return lockFile !== undefined;63 });64 }65}...

Full Screen

Full Screen

SafetyStorage.js

Source:SafetyStorage.js Github

copy

Full Screen

1import os from 'os';2import path from 'path';3import lockfile from 'lockfile';4import { newLogger } from '@dbux/common/src/log/logger';5const { log, debug, warn, error: logError } = newLogger('SavetyStorage');6let storageGet, storageSet;7function getLockfileName(name) {8 let lockfilePath = path.join(os.tmpdir(), `dbux-lockfile.${name}`);9 return lockfilePath;10}11async function acquireLock(name) {12 return new Promise((resolve, reject) => {13 lockfile.lock(getLockfileName(name), { wait: 10 ** 9 }, (err) => {14 if (err) {15 reject(err);16 }17 else {18 resolve();19 }20 });21 });22}23export default class SafetyStorage {24 constructor(name) {25 this.name = name;26 }27 async acquireLock() {28 return acquireLock(this.name);29 }30 releaseLock() {31 lockfile.unlockSync(getLockfileName(this.name));32 }33 get() {34 return storageGet(this.name);35 }36 async set(value) {37 await storageSet(this.name, value);38 }39}40export function initSafetyStorage(storageFunctions) {41 ({ get: storageGet, set: storageSet } = storageFunctions);...

Full Screen

Full Screen

index.sepc.js

Source:index.sepc.js Github

copy

Full Screen

1/* eslint-env jest */2// @flow3import assert from "assert";4import path from "path";5import Npm from "../src/index";6test("Npm#match should returns true if directory have package.json", async () => {7 const npm = new Npm();8 assert.ok(await npm.match(path.join(__dirname, "fixtures", "is-npm")));9});10test("Npm#match should returns false if directory not have package.json", async () => {11 const npm = new Npm();12 assert.ok(!(await npm.match(path.join(__dirname, "fixtures", "not-npm"))));13});14test("Npm#getLockFileName should returns package-lock.json", async () => {15 const npm = new Npm();16 assert.ok(npm.getLockFileName(), "package-lock.json");...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const getLockFilename = require('cypress/lib/util/lock')2const lockFile = getLockFilename()3console.log(lockFile)4const getLockFilename = require('cypress/lib/util/lock')5const lockFile = getLockFilename()6console.log(lockFile)7const getLockFilename = require('cypress/lib/util/lock')8const lockFile = getLockFilename()9console.log(lockFile)10const getLockFilename = require('cypress/lib/util/lock')11const lockFile = getLockFilename()12console.log(lockFile)13const getLockFilename = require('cypress/lib/util/lock')14const lockFile = getLockFilename()15console.log(lockFile)

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress')2const filename = cypress.runner.getLockFilename()3console.log(filename)4const cypress = require('cypress')5const filename = cypress.runner.getLockFilename()6console.log(filename)7module.exports = (on, config) => {8 on('task', {9 getLockFilename () {10 return cypress.runner.getLockFilename()11 },12 })13}14Cypress.Commands.add('getLockFilename', () => {15 return cy.task('getLockFilename')16})17describe('Test', () => {18 it('test', () => {19 cy.getLockFilename().then(filename => {20 console.log(filename)21 })22 })23})

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path')2const getLockFilename = require('cypress/lib/util/lock').getLockFilename3const lockFile = getLockFilename(path.resolve(__dirname, '..'))4console.log('lockFile', lockFile)5const path = require('path')6const getLockFilename = require('cypress/lib/util/lock').getLockFilename7const lockFile = getLockFilename(path.resolve(__dirname, '..'))8console.log('lockFile', lockFile)

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress');2const path = require('path');3const lockFile = cypress.getLockFilename();4console.log('Lock file name: ', lockFile);5console.log('Lock file path: ', path.join(process.cwd(), lockFile));6const cypress = require('cypress');7const path = require('path');8const os = require('os');9const fs = require('fs');10const lockFile = cypress.getLockFilename();11const lockFilePath = path.join(process.cwd(), lockFile);12const numberOfCpus = os.cpus().length;13fs.writeFileSync(lockFilePath, new Date().toISOString());14cypress.run({15 reporterOptions: {16 },17}).then((results) => {18 fs.unlinkSync(lockFilePath);19 console.log(results);20});21"scripts": {22}23const cypress = require('cypress');24const path = require('path');25const os = require('os');26const fs = require('fs');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { getLockFilename } = require('cypress/lib/util/lock')2const lockFile = getLockFilename()3console.log(lockFile)4const { getLockFilename } = require('cypress/lib/util/lock')5const lockFile = getLockFilename()6console.log(lockFile)7const { getLockFilename } = require('cypress/lib/util/lock')8const lockFile = getLockFilename()9console.log(lockFile)10const { getLockFilename } = require('cypress/lib/util/lock')11const lockFile = getLockFilename()12console.log(lockFile)13const { getLockFilename } = require('cypress/lib/util/lock')14const lockFile = getLockFilename()15console.log(lockFile)16const { getLockFilename } = require('cypress/lib/util/lock')17const lockFile = getLockFilename()18console.log(lockFile)19const { getLockFilename } = require('cypress/lib/util/lock')20const lockFile = getLockFilename()21console.log(lockFile)22const { getLockFilename } = require('cypress/lib/util/lock')23const lockFile = getLockFilename()24console.log(lockFile)

Full Screen

Using AI Code Generation

copy

Full Screen

1const cypress = require('cypress')2const path = require('path')3const fs = require('fs-extra')4console.log(cypress.getLockFilename())5const cypressCachePath = path.join(6 require('os').homedir(),7console.log(cypressCachePath)8const cypressCachePath = path.join(9 require('os').homedir(),10console.log(cypressCachePath)11const cypressCachePath = path.join(12 require('os').homedir(),13console.log(cypressCachePath)14const cypressCachePath = path.join(15 require('os').homedir(),16console.log(cypressCachePath)17const cypressCachePath = path.join(18 require('os').homedir(),19console.log(cypressCachePath)20const cypressCachePath = path.join(21 require('os').homedir(),22console.log(cypressCachePath)23const cypressCachePath = path.join(24 require('os').homedir(),25console.log(cypressCachePath)26const cypressCachePath = path.join(27 require('os').homedir(),28console.log(cypressCachePath)29const cypressCachePath = path.join(30 require('os').homedir(),31console.log(cypressCachePath)32const cypressCachePath = path.join(33 require('os').homedir(),34console.log(cypressCachePath)35const cypressCachePath = path.join(36 require('os').homedir(),37console.log(cypressCachePath)

Full Screen

Using AI Code Generation

copy

Full Screen

1const lockFile = Cypress.getLockFilename()2console.log('lockFile', lockFile)3const lockFile = Cypress.getLockFilename()4console.log('lockFile', lockFile)5const lockFile = Cypress.getLockFilename()6console.log('lockFile', lockFile)7const lockFile = Cypress.getLockFilename()8console.log('lockFile', lockFile)9const lockFile = Cypress.getLockFilename()10console.log('lockFile', lockFile)11const lockFile = Cypress.getLockFilename()12console.log('lockFile', lockFile)13const lockFile = Cypress.getLockFilename()14console.log('lockFile', lockFile)15const lockFile = Cypress.getLockFilename()16console.log('lockFile', lockFile)17const lockFile = Cypress.getLockFilename()18console.log('lockFile', lockFile)19const lockFile = Cypress.getLockFilename()20console.log('lockFile', lockFile)21const lockFile = Cypress.getLockFilename()22console.log('lockFile', lockFile)23const lockFile = Cypress.getLockFilename()24console.log('lockFile

Full Screen

Using AI Code Generation

copy

Full Screen

1const path = require('path');2const cypress = require('cypress');3cypress.run({4 config: {5 },6 env: {7 },8 spec: path.join(__dirname, 'spec.js'),9}).then((results) => {10 console.log(results);11}).catch((err) => {12 console.error(err);13});14const path = require('path');15const cypress = require('cypress');16cypress.run({17 config: {18 },19 env: {20 },21 spec: path.join(__dirname, 'spec.js'),22}).then((results) => {23 console.log(results);24}).catch((err) => {25 console.error(err);26});27const path = require('path');28const cypress = require('cypress');29cypress.run({30 config: {31 },32 env: {33 },34 spec: path.join(__dirname, 'spec.js'),35}).then((results) => {36 console.log(results);37}).catch((err) => {38 console.error(err);39});40const path = require('path');41const cypress = require('cypress');42cypress.run({43 config: {44 },45 env: {46 },47 spec: path.join(__dirname, 'spec.js'),48}).then((results) => {49 console.log(results);50}).catch((err) => {51 console.error(err);52});53const path = require('path');54const cypress = require('cypress');55cypress.run({56 config: {57 },58 env: {

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