How to use fs.readdirAsync method in Cypress

Best JavaScript code snippet using cypress

ci.js

Source:ci.js Github

copy

Full Screen

...90 stdout.trim(),91 /\nasdf\nadded 6 packages in \d+(?:\.\d+)?s$/,92 'no warnings on stderr, and final output has right number of packages'93 )94 return fs.readdirAsync(path.join(testDir, 'node_modules'))95 })96 .then((modules) => {97 t.deepEqual(modules.sort(), [98 'async', 'checker', 'clean', 'minimist', 'optimist', 'wordwrap'99 ], 'packages installed')100 return BB.all(modules.map((mod) => {101 return fs.readFileAsync(102 path.join(testDir, 'node_modules', mod, 'package.json')103 )104 .then((f) => JSON.parse(f))105 .then((pkgjson) => {106 t.equal(pkgjson.name, mod, `${mod} package name correct`)107 t.match(108 pkgjson._integrity,109 /sha\d+-[a-z0-9=+/]+$/i,110 `${mod} pkgjson has _integrity`111 )112 t.match(113 pkgjson._resolved,114 new RegExp(`http.*/-/${mod}-${pkgjson.version}.tgz`),115 `${mod} pkgjson has correct _resolved`116 )117 t.match(118 pkgjson._from,119 new RegExp(`${mod}@.*`),120 `${mod} pkgjson has _from field`121 )122 })123 }))124 })125 .then(() => fs.readFileAsync(126 path.join(testDir, 'package-lock.json'),127 'utf8')128 )129 .then((lock) => t.equal(lock, RAW_LOCKFILE, 'package-lock.json unchanged'))130 .then(() => common.npm(['ls', '--json'], EXEC_OPTS))131 .then((ret) => {132 const lsResult = JSON.parse(ret[1])133 t.equal(ret[0], 0, 'ls exited successfully')134 t.deepEqual(scrubFrom(lsResult), TREE, 'tree matches one from `install`')135 })136})137test('supports npm-shrinkwrap.json as well', (t) => {138 const fixture = new Tacks(Dir({139 'package.json': File(PKG),140 'npm-shrinkwrap.json': File(RAW_LOCKFILE)141 }))142 return rimraf(testDir)143 .then(() => fixture.create(testDir))144 .then(() => common.npm([145 'ci',146 '--foo=asdf',147 '--registry', common.registry,148 '--loglevel', 'warn'149 ], EXEC_OPTS))150 .then((ret) => {151 const code = ret[0]152 const stdout = ret[1]153 const stderr = ret[2]154 t.equal(code, 0, 'command completed without error')155 t.equal(stderr.trim(), '', 'no output on stderr')156 t.match(157 stdout.trim(),158 /\nasdf\nadded 6 packages in \d+(?:\.\d+)?s$/,159 'no warnings on stderr, and final output has right number of packages'160 )161 })162 .then(() => common.npm(['ls', '--json'], EXEC_OPTS))163 .then((ret) => {164 t.equal(ret[0], 0, 'ls exited successfully')165 t.deepEqual(166 scrubFrom(JSON.parse(ret[1])),167 TREE,168 'tree matches one from `install`'169 )170 })171 .then(() => fs.readFileAsync(172 path.join(testDir, 'npm-shrinkwrap.json'),173 'utf8')174 )175 .then((lock) => t.equal(lock, RAW_LOCKFILE, 'npm-shrinkwrap.json unchanged'))176 .then(() => fs.readdirAsync(path.join(testDir)))177 .then((files) => t.notOk(178 files.some((f) => f === 'package-lock.json'),179 'no package-lock.json created'180 ))181})182test('removes existing node_modules/ before installing', (t) => {183 const fixture = new Tacks(Dir({184 'package.json': File(PKG),185 'package-lock.json': File(RAW_LOCKFILE),186 'node_modules': Dir({187 foo: Dir({188 'index.js': File('"hello world"')189 })190 })191 }))192 return rimraf(testDir)193 .then(() => fixture.create(testDir))194 .then(() => common.npm([195 'ci',196 '--foo=asdf',197 '--registry', common.registry,198 '--loglevel', 'warn'199 ], EXEC_OPTS))200 .then((ret) => {201 const code = ret[0]202 const stderr = ret[2]203 t.equal(code, 0, 'command completed without error')204 t.match(205 stderr.trim(),206 /^npm.*WARN.*removing existing node_modules/,207 'user warned that existing node_modules were removed'208 )209 return fs.readdirAsync(path.join(testDir, 'node_modules'))210 })211 .then((modules) => {212 t.deepEqual(modules.sort(), [213 'async', 'checker', 'clean', 'minimist', 'optimist', 'wordwrap'214 ], 'packages installed, with old node_modules dir gone')215 })216 .then(() => common.npm(['ls'], EXEC_OPTS))217 .then((ret) => t.equal(ret[0], 0, 'ls exited successfully'))218 .then(() => fs.readFileAsync(219 path.join(testDir, 'package-lock.json'),220 'utf8')221 )222 .then((lock) => t.equal(lock, RAW_LOCKFILE, 'package-lock.json unchanged'))223})224test('installs all package types correctly')225test('errors if package-lock.json missing', (t) => {226 const fixture = new Tacks(Dir({227 'package.json': File(PKG)228 }))229 return rimraf(testDir)230 .then(() => fixture.create(testDir))231 .then(() => common.npm([232 'ci',233 '--foo=asdf',234 '--registry', common.registry,235 '--loglevel', 'warn'236 ], EXEC_OPTS))237 .then((ret) => {238 const code = ret[0]239 const stdout = ret[1]240 const stderr = ret[2]241 t.equal(code, 1, 'command errored')242 t.equal(stdout.trim(), '', 'no output on stdout')243 t.match(244 stderr.trim(),245 /can only install packages with an existing package-lock/i,246 'user informed about the issue'247 )248 return fs.readdirAsync(path.join(testDir))249 })250 .then((dir) => {251 t.notOk(dir.some((f) => f === 'node_modules'), 'no node_modules installed')252 t.notOk(253 dir.some((f) => f === 'package-lock.json'),254 'no package-lock.json created'255 )256 })257})258test('errors if package-lock.json invalid', (t) => {259 const badJson = JSON.parse(RAW_LOCKFILE)260 delete badJson.dependencies.optimist261 const fixture = new Tacks(Dir({262 'package.json': File(PKG),263 'package-lock.json': File(badJson)264 }))265 return rimraf(testDir)266 .then(() => fixture.create(testDir))267 .then(() => common.npm([268 'ci',269 '--foo=asdf',270 '--registry', common.registry,271 '--loglevel', 'warn'272 ], EXEC_OPTS))273 .then((ret) => {274 const code = ret[0]275 const stdout = ret[1]276 const stderr = ret[2]277 t.equal(code, 1, 'command errored')278 t.equal(stdout.trim(), '', 'no output on stdout')279 t.match(280 stderr.trim(),281 /can only install packages when your package.json/i,282 'user informed about the issue'283 )284 return fs.readdirAsync(path.join(testDir))285 })286 .then((dir) => {287 t.notOk(dir.some((f) => f === 'node_modules'), 'no node_modules installed')288 })289 .then(() => fs.readFileAsync(290 path.join(testDir, 'package-lock.json'),291 'utf8')292 )293 .then((lock) => t.deepEqual(294 JSON.parse(lock),295 badJson,296 'bad package-lock.json left unchanged')297 )298})299test('correct cache location when using cache config', (t) => {300 const fixture = new Tacks(Dir({301 'package.json': File(PKG),302 'package-lock.json': File(RAW_LOCKFILE)303 }))304 return Promise.all([rimraf(cacheDir), rimraf(testDir)])305 .then(() => fixture.create(cacheDir))306 .then(() => fixture.create(testDir))307 .then(() => common.npm([308 'ci',309 `--cache=${cacheDir}`,310 '--foo=asdf',311 '--registry', common.registry,312 '--loglevel', 'warn'313 ], EXEC_OPTS))314 .then((ret) => {315 const code = ret[0]316 const stderr = ret[2]317 t.equal(code, 0, 'command completed without error')318 t.equal(stderr.trim(), '', 'no output on stderr')319 return fs.readdirAsync(path.join(cacheDir, '_cacache'))320 })321 .then((modules) => {322 t.ok(modules, 'should create _cacache folder')323 t.end()324 })325})326test('cleanup', () => {327 SERVER.close()328 return Promise.all([rimraf(cacheDir), rimraf(testDir)])...

Full Screen

Full Screen

db.spec.js

Source:db.spec.js Github

copy

Full Screen

1/* eslint-env jest */2jest.mock('fs', () => ({3 mkdirAsync: jest.fn(),4 writeFileAsync: jest.fn(),5 readFileAsync: jest.fn(),6 readdirAsync: jest.fn(),7}))8const fs = require('fs')9const db = require('./db')10const getState = () => ({11 component: {12 path: {13 absolute: {14 workbench: '/a/path/.workbench',15 },16 },17 },18})19describe('server/api/db', () => {20 beforeEach(() => {21 fs.mkdirAsync.mockClear()22 fs.writeFileAsync.mockClear()23 fs.readFileAsync.mockClear()24 fs.readdirAsync.mockClear()25 fs.mkdirAsync.mockImplementation(jest.fn())26 fs.writeFileAsync.mockImplementation(jest.fn())27 fs.readFileAsync.mockImplementation(jest.fn())28 fs.readdirAsync.mockImplementation(jest.fn())29 })30 describe('init', () => {31 it('should provide db service', () => {32 // calls33 const service = db('foo')(undefined, getState)34 // asserts35 expect(service).toBeDefined()36 expect(typeof service.write).toBe('function')37 expect(typeof service.read).toBe('function')38 expect(typeof service.append).toBe('function')39 })40 })41 describe('write', () => {42 const content = ['foo', 'bar']43 it('should create the configuration directory', async () => {44 // calls45 const data = await db()(undefined, getState).write('fileName.jsx', content)46 // asserts47 expect(data).toBeDefined()48 expect(fs.mkdirAsync.mock.calls.length).toBe(1)49 expect(fs.mkdirAsync.mock.calls[0][0]).toBe('/a/path/.workbench')50 })51 it('should pass when configuration directory exists', async () => {52 // mocks53 fs.mkdirAsync.mockImplementation(jest.fn(async () => {54 const error = { errno: -17 }55 throw error56 }))57 // calls58 const data = await db()(undefined, getState).write('fileName.jsx', content)59 // asserts60 expect(data).toBeDefined()61 expect(fs.writeFileAsync.mock.calls.length).toBe(1)62 })63 it('should write data into the directory', async () => {64 // calls65 const data = await db()(undefined, getState).write('aComponent.jsx.json', content)66 // asserts67 expect(data).toBeDefined()68 expect(data).toEqual(content)69 expect(fs.writeFileAsync.mock.calls.length).toBe(1)70 expect(fs.writeFileAsync.mock.calls[0][0]).toBe('/a/path/.workbench/aComponent.jsx.json')71 expect(fs.writeFileAsync.mock.calls[0][1]).toBe(JSON.stringify(data))72 })73 it('should init an empty configuration when given data are undefined', async () => {74 // calls75 const data = await db()(undefined, getState).write('fileName.jsx', undefined)76 // asserts77 expect(data).toBeDefined()78 expect(data).toEqual([])79 })80 describe('errors', () => {81 it('should throw an error when unexpected fs error happens', async () => {82 // mocks83 fs.mkdirAsync.mockImplementation(jest.fn(async () => {84 throw new Error()85 }))86 // calls87 let error = false88 try {89 await db()(undefined, getState).write(content)90 } catch (ex) {91 error = true92 }93 // asserts94 expect(error).toBe(true)95 })96 })97 })98 describe('read', () => {99 it('should read the configuration if exists', async () => {100 // mocks101 fs.readFileAsync.mockImplementation(jest.fn(async () => '[ "foo" ]'))102 // calls103 const data = await db()(undefined, getState).read('aComponent.jsx.json')104 // asserts105 expect(data).toBeDefined()106 expect(data).toEqual(['foo'])107 expect(fs.readFileAsync.mock.calls.length).toBe(1)108 expect(fs.readFileAsync.mock.calls[0][0]).toBe('/a/path/.workbench/aComponent.jsx.json')109 })110 it('should return "undefined" if configuration file doesn\'t exists', async () => {111 // mocks112 fs.readFileAsync.mockImplementation(jest.fn(async () => {113 const error = { errno: -2 }114 throw error115 }))116 // calls117 const data = await db()(undefined, getState).read('fileName.json')118 // asserts119 expect(data).toBeUndefined()120 })121 describe('errors', () => {122 it('should throw an error when unexpected fs error happens', async () => {123 // mocks124 fs.readFileAsync.mockImplementation(jest.fn(async () => {125 throw new Error()126 }))127 // calls128 let error = false129 try {130 await db()(undefined, getState).read()131 } catch (ex) {132 error = true133 }134 // asserts135 expect(error).toBe(true)136 })137 })138 })139 describe('append', () => {140 // data141 const content = ['foo', 'bar']142 it('should return an empty configuration if doesn\'t exists and nothing to append', async () => {143 // calls144 const result = await db()(undefined, getState).append('fileName.jsx', undefined)145 // asserts146 expect(result).toBeDefined()147 expect(result).toEqual([])148 })149 it('should return the current configuration if exists and nothing to append', async () => {150 // mocks151 fs.readFileAsync.mockImplementation(jest.fn(async () => '[ "foo" ]'))152 // calls153 const result = await db()(undefined, getState).append('testedComponent.jsx', undefined)154 // asserts155 expect(result).toBeDefined()156 expect(result).toEqual(['foo'])157 })158 it('should append & write content to an empty configuration', async () => {159 // calls160 const result = await db()(undefined, getState).append('testedComponent.jsx', content)161 // asserts162 expect(result).toBeDefined()163 expect(result).toEqual(['foo', 'bar'])164 })165 it('should append & write content to the existing configuration', async () => {166 // mocks167 fs.readFileAsync.mockImplementation(jest.fn(async () => '[ "baz" ]'))168 // calls169 const result = await db()(undefined, getState).append('testedComponent.jsx', content)170 // asserts171 expect(result).toBeDefined()172 expect(result).toEqual(['baz', 'foo', 'bar'])173 })174 describe('list', () => {175 it('should list read all files in a directory', async () => {176 // mocks177 fs.readdirAsync.mockImplementation(jest.fn(() => ['file 1', 'file 2']))178 // calls179 const result = await db()(undefined, getState).list()180 // asserts181 expect(result).toMatchSnapshot()182 expect(fs.readdirAsync.mock.calls).toMatchSnapshot()183 })184 it('should handle an empty directory', async () => {185 // mocks186 fs.readdirAsync.mockImplementation(jest.fn(() => []))187 // calls188 const result = await db()(undefined, getState).list()189 // asserts190 expect(result).toMatchSnapshot()191 expect(fs.readdirAsync.mock.calls).toMatchSnapshot()192 })193 it('should throw the underlaying fs exception', async () => {194 // mocks195 fs.readdirAsync.mockImplementation(jest.fn(() => {196 throw new Error('fs readdir error')197 }))198 // calls199 let error = false200 try {201 await db()(undefined, getState).list()202 } catch (ex) {203 error = ex204 }205 // asserts206 expect(error).toMatchSnapshot()207 expect(fs.readdirAsync.mock.calls).toMatchSnapshot()208 })209 })210 })...

Full Screen

Full Screen

ivectors-tools.test.js

Source:ivectors-tools.test.js Github

copy

Full Screen

...19 describe('#normPRM', () => {20 it('should normalize prm files', function () {21 this.timeout(0);22 return normPRM(firstLayer)23 .then(() => fs.readdirAsync(firstLayer.paths.prm))24 .then(files => {25 const prm = files.filter(f => !f.match(/\.norm/g));26 const normPrm = files.filter(f => f.match(/\.norm/g));27 normPrm.length.should.be.equal(prm.length);28 normPrm.map(file => file.split('.')[0]).should.be.deep29 .equal(prm.map(file => file.split('.')[0]));30 });31 });32 });33 describe('#createUBM', () => {34 before(function () {35 this.timeout(0);36 return fs.removeAsync(workbench.gmm)37 .then(() => createUBM(firstLayer, workbench))38 .catch(() => {});39 });40 it('should have created files world.gmm and worldinit.gmm', () => {41 return fs.readdirAsync(workbench.gmm)42 .then(files => {43 files.length.should.be.equal(2);44 files.should.be.deep.equal(['world.gmm', 'worldinit.gmm']);45 });46 });47 });48 describe('#createTV', () => {49 before(function () {50 this.timeout(0);51 return fs.removeAsync(workbench.mat)52 .then(() => createTV(firstLayer, workbench))53 .catch(() => {});54 });55 it('should have created TV.matx and other files', () => {56 return fs.readdirAsync(workbench.mat)57 .then(files => {58 files.should.include('TV.matx');59 files.should.include('TV_F_X.matx');60 files.should.include('TV_init.matx');61 files.should.include('TV_N.matx');62 files.should.include('newMeanMinDiv_it.matx');63 });64 });65 });66 describe('#ivExtractor', () => {67 const inputFiles = [];68 const inputClusters = [];69 before(() => {70 return fs.removeAsync(workbench.ivRaw)71 .then(() => fs.readdirAsync(`${firstLayer.paths.input}/f1`))72 .then(clusters => {73 inputClusters.push(...clusters);74 return BluebirdPromise.all([75 BluebirdPromise.map(clusters, cluster => fs.readdirAsync(76 `${firstLayer.paths.input}/f1/${cluster}`)),77 fs.readdirAsync(`${firstLayer.paths.test}/f1`)78 ]);79 })80 .then(([inputFilesList, testFilesList]) => {81 inputFilesList.forEach(list => {82 inputFiles.push(...list.map(file => file.replace('.wav', '')));83 });84 inputFiles.push(85 ...testFilesList.map(file => file.replace('.wav', '')));86 inputFiles.sort();87 });88 });89 it('should extract all single ivectors', function () {90 this.timeout(0);91 return ivExtractor(firstLayer, workbench, 'ivExtractorAll.ndx')92 .then(() => fs.readdirAsync(workbench.ivRaw))93 .then(ivRaw => {94 ivRaw.length.should.be.equal(inputFiles.length);95 ivRaw.map(iv => iv.replace('.y', '')).should.be.deep96 .equal(inputFiles);97 });98 });99 it('should extract concatenated vectors', function () {100 this.timeout(0);101 return ivExtractor(firstLayer, workbench, 'ivExtractor.ndx')102 .then(() => fs.readdirAsync(workbench.ivRaw))103 .then(ivRaw => {104 ivRaw.length.should.be.equal(105 inputFiles.length + inputClusters.length);106 ivRaw.map(iv => iv.replace('.y', '')).should.include107 .members(inputClusters);108 });109 });110 });111 describe('#normalizePLDA', () => {112 before(() => {113 return fs.removeAsync(workbench.ivLenNorm);114 });115 it('should have the same number of files than ivectors', function () {116 this.timeout(0);117 return normalizePLDA(firstLayer, workbench)118 .then(() => BluebirdPromise.all([119 fs.readdirAsync(workbench.ivLenNorm),120 fs.readdirAsync(workbench.ivRaw)121 ]))122 .then(([norm, raw]) => {123 norm.length.should.be.equal(raw.length);124 norm.should.be.deep.equal(raw);125 return fs.readdirAsync(workbench.mat);126 })127 .then(filesList => {128 filesList.should.include('EfrMat0.matx');129 filesList.should.include('EfrMean0.matx');130 });131 });132 });133 describe('#createSph', () => {134 it('should create the appropriates matrices for sph scoring', () => {135 return createSph(firstLayer, workbench)136 .then(() => fs.readdirAsync(workbench.mat))137 .then(filesList => {138 filesList.should.include.members([139 'plda_SphNorm_G.matx',140 'plda_SphNorm_minDivMean.matx',141 'plda_SphNorm_originalMean.matx',142 'plda_SphNorm_Sigma.matx',143 'sphNorm_SphNormMat0.matx',144 'sphNorm_SphNormMat1.matx',145 'sphNorm_SphNormMean0.matx',146 'sphNorm_SphNormMean1.matx'147 ]);148 });149 });150 });151 describe('#trainPLDA', () => {152 it('should create the appropriates matrices for PLDA scoring', () => {153 return trainPLDA(firstLayer, workbench)154 .then(() => fs.readdirAsync(workbench.mat))155 .then(filesList => {156 filesList.should.include.members([157 'plda_F.matx',158 'plda_G.matx',159 'plda_minDivMean.matx',160 'plda_originalMean.matx',161 'plda_Sigma.matx'162 ]);163 });164 });165 });166 describe('#scoreSph', () => {167 it('should score all test files', () => {168 return scoreSph(workbench)169 .then(() => fs.readdirAsync(workbench.scores.sph))170 .then(filesList => {171 filesList.should.include('1.txt');172 return BluebirdPromise.all([173 fs.readFileAsync(`${workbench.scores.sph}/1.txt`),174 fs.readdirAsync(`${firstLayer.paths.input}/f1`),175 fs.readdirAsync(`${firstLayer.paths.test}/f1`)176 ]);177 })178 .then(([results, inputClusters, testFiles]) => {179 results.toString().split('\n').filter(line => line !== '').length180 .should.be.equal(inputClusters.length * testFiles.length);181 });182 });183 });184 describe('#scorePLDA', () => {185 it('should score all test files', () => {186 return scorePLDA(workbench)187 .then(() => fs.readdirAsync(workbench.scores.plda))188 .then(filesList => {189 filesList.should.include('1.txt');190 return BluebirdPromise.all([191 fs.readFileAsync(`${workbench.scores.plda}/1.txt`),192 fs.readdirAsync(`${firstLayer.paths.input}/f1`),193 fs.readdirAsync(`${firstLayer.paths.test}/f1`)194 ]);195 })196 .then(([results, inputClusters, testFiles]) => {197 results.toString().split('\n').filter(line => line !== '').length198 .should.be.equal(inputClusters.length * testFiles.length);199 });200 });201 });...

Full Screen

Full Screen

static-files-api-service-spec.js

Source:static-files-api-service-spec.js Github

copy

Full Screen

1// Copyright 2016, EMC, Inc.2/* jshint node:true */3"use strict";4describe("Http.Services.Api.StaticFiles", function () {5 var path;6 var staticFilesApiService;7 var waterline;8 before("Http.Services.Api.StaticFiles before", function() {9 helper.setupInjector([10 helper.require("/lib/services/static-files-api-service.js")11 ]);12 staticFilesApiService = helper.injector.get("Http.Services.Api.StaticFiles");13 path = helper.injector.get('path');14 waterline = helper.injector.get('Services.Waterline');15 waterline.skus = {16 findOne:function() {}17 };18 this.sandbox = sinon.sandbox.create();19 });20 afterEach("Http.Services.Api.StaticFiles afterEach", function() {21 this.sandbox.restore();22 });23 describe("pairSkupackIds", function() {24 var nodeFs;25 before(function() {26 nodeFs = helper.injector.get('fs');27 sinon.stub(nodeFs, 'lstatAsync');28 sinon.stub(nodeFs, 'readdirAsync');29 this.sandbox.stub(waterline.skus, 'findOne');30 });31 beforeEach(function() {32 nodeFs.lstatAsync.reset();33 nodeFs.readdirAsync.reset();34 });35 after(function () {36 nodeFs.lstatAsync.restore();37 nodeFs.readdirAsync.restore();38 });39 it('should return an id:sku pair given valid directories and database', function() {40 nodeFs.readdirAsync.resolves(['567432']);41 nodeFs.lstatAsync.resolves({ isDirectory: function() { return true; }});42 waterline.skus.findOne.resolves({43 id: '567432',44 name: 'testSku'45 });46 return staticFilesApiService.pairSkupackIds([]).then(function(value) {47 expect(nodeFs.readdirAsync).to.have.been.called;48 expect(nodeFs.lstatAsync).to.have.been.called;49 expect(waterline.skus.findOne).to.have.been.called;50 expect(value).to.deep.equal({'567432': 'testSku'});51 });52 });53 it('returns {} when there is no sku data in the database', function() {54 nodeFs.readdirAsync.resolves(['123']);55 nodeFs.lstatAsync.resolves({ isDirectory: function() { return true; }});56 var stubFind = sinon.stub(waterline.skus, "findOne");57 stubFind.rejects(new Error('Error: no available sku in the db'));58 return staticFilesApiService.pairSkupackIds([]).then(function(value) {59 expect(nodeFs.readdirAsync).to.have.been.called;60 expect(nodeFs.lstatAsync).to.have.been.called;61 expect(waterline.skus.findOne).to.have.been.called;62 expect(value).to.deep.equal({});63 });64 });65 });66 describe("walkDirectory", function() {67 it('returns an array of file names following "static" in the path', function() {68 var dirPath = path.join("spec/mocks/static");69 var result = [ 70 { uri: 'found' },71 { uri: 'foundFile2' }72 ];73 return staticFilesApiService.walkDirectory(dirPath).then(function(value) {74 expect(value).to.deep.equal(result);75 });76 });77 it('returns an array of file names following "skupack.d" in the path', function() {78 var dirPath = "spec/mocks/skupack.d";79 var result = [80 {81 sku: "mocks",82 uri: "sku-id/static/found-2"83 },84 {85 sku: "mocks",86 uri: "sku-id/static/common/found-3"87 }88 ];89 return staticFilesApiService.walkDirectory(dirPath).then(function(value) {90 expect(value).to.deep.equal(result);91 });92 });93 it('returns [] when provided a bad path', function() {94 var dirPath;95 var result = [];96 return staticFilesApiService.walkDirectory(dirPath).then(function(value) {97 expect(value).to.deep.equal(result);98 });99 });100 });101 describe("getAllStaticFiles", function() {102 var nodeFs;103 before(function() {104 nodeFs = helper.injector.get('fs');105 sinon.stub(nodeFs, 'lstatAsync');106 sinon.stub(staticFilesApiService, 'pairSkupackIds');107 sinon.stub(staticFilesApiService, 'walkDirectory');108 });109 beforeEach(function() {110 nodeFs.lstatAsync.reset();111 });112 after(function () {113 nodeFs.lstatAsync.restore();114 });115 it('returns a single array of objects with static file data', function() {116 var result = [117 {118 "uri": "found"119 },120 {121 "uri": "foundFile2"122 },123 {124 "sku": "testSku",125 "uri": "found-2"126 },127 {128 "sku": "testSku",129 "uri": "common/found-3"130 }131 ];132 var pair = {133 '567432': 'testSku'134 };135 var walkFirst = [136 {137 uri: 'found'138 },139 {140 uri: 'foundFile2'141 }142 ];143 var walkSecond = [144 {145 sku: "567432",146 uri: "found-2"147 },148 {149 sku: "567432",150 uri: "common/found-3"151 }152 ];153 var walkThird = [];154 staticFilesApiService.pairSkupackIds.resolves(pair);155 staticFilesApiService.walkDirectory156 .onFirstCall().resolves(walkFirst)157 .onSecondCall().resolves(walkSecond)158 .onThirdCall().resolves(walkThird);159 return staticFilesApiService.getAllStaticFiles().then(function(value) {160 expect(value).to.deep.equal(result);161 });162 });163 it('returns [] given no valid dirs to walk or those dirs are empty', function() {164 nodeFs.lstatAsync.resolves({ isDirectory: function() { return false; }});165 staticFilesApiService.walkDirectory.resolves([]);166 return staticFilesApiService.getAllStaticFiles().then(function(value) {167 expect(value).to.deep.equal([]);168 });169 });170 });...

Full Screen

Full Screen

task-option-validator-spec.js

Source:task-option-validator-spec.js Github

copy

Full Screen

1// Copyright 2016, EMC2'use strict';3describe("TaskOption Validator", function () {4 var taskOptionValidator;5 var testSchema1 = {6 id: 'test1',7 properties: {8 repo: {9 type: 'string',10 format: 'uri'11 }12 }13 };14 var testSchema2 = {15 id: 'test2',16 test: 'test meta schema required property',17 definitions: {18 VlanId: {19 type: 'integer',20 minimum: 0,21 maximum: 409522 }23 },24 properties: {25 vlanId: {26 $ref: '#/definitions/VlanId'27 },28 vesrion: {29 type: 'string'30 }31 }32 };33 var testMetaSchema = {34 properties: {35 test: {36 type: 'string'37 }38 },39 required: ['test']40 };41 before(function() {42 helper.setupInjector([43 helper.require('/lib/utils/task-option-validator')44 ]);45 taskOptionValidator = helper.injector.get('TaskOption.Validator');46 });47 describe('register', function() {48 var nodeFs;49 before(function () {50 nodeFs = helper.injector.get('fs');51 sinon.stub(nodeFs, 'readdirAsync');52 sinon.stub(nodeFs, 'readFileAsync'); 53 });54 beforeEach(function () {55 nodeFs.readdirAsync.reset();56 nodeFs.readFileAsync.reset();57 });58 afterEach(function () {59 taskOptionValidator.reset();60 delete testSchema2.$schema; 61 });62 after(function () {63 nodeFs.readdirAsync.restore();64 nodeFs.readFileAsync.restore();65 });66 it('should load all JSON schemas in default folder', function() {67 testSchema2.$schema = 'rackhd-task-schema.json';68 nodeFs.readdirAsync.resolves([69 'testSchema1.json',70 'testSchema2.json',71 'rackhd-task-schema.json'72 ]);73 nodeFs.readFileAsync.onCall(0).resolves(JSON.stringify(testSchema1));74 nodeFs.readFileAsync.onCall(1).resolves(JSON.stringify(testSchema2));75 nodeFs.readFileAsync.onCall(2).resolves(JSON.stringify(testMetaSchema));76 return taskOptionValidator.register()77 .then(function () {78 expect(nodeFs.readdirAsync).to.be.calledOnce;79 expect(nodeFs.readFileAsync).to.have.calledThrice;80 expect(taskOptionValidator.getSchema('testSchema1.json')).to.have.property('id')81 .that.equals('testSchema1.json');82 expect(taskOptionValidator.getSchema('testSchema2.json')).to.have.property('id')83 .that.equals('testSchema2.json');84 });85 });86 it('should load all JSON schemas in specific folder', function() {87 nodeFs.readdirAsync.resolves([88 'testSchema2.json',89 'testMetaSchema.json'90 ]);91 nodeFs.readFileAsync.onCall(0).resolves(JSON.stringify(testSchema2));92 nodeFs.readFileAsync.onCall(1).resolves(JSON.stringify(testMetaSchema));93 return taskOptionValidator.register('/home', 'testMetaSchema.json')94 .then(function () {95 expect(nodeFs.readdirAsync).to.be.calledOnce;96 expect(nodeFs.readFileAsync).to.have.calledTwice;97 expect(taskOptionValidator.getSchema('testSchema2.json')).to.have.property('id')98 .that.equals('testSchema2.json');99 });100 });101 });102 describe('validateContextSkipped', function () {103 it('should return true when validation pass', function () {104 var result = taskOptionValidator.validateContextSkipped(testSchema1,105 { repo : '/172.31.128.1/mirrors' });106 expect(result).to.be.true;107 });108 it('should return true and skip error with context render', function () {109 var result = taskOptionValidator.validateContextSkipped(testSchema1,110 { repo : '{{ context.baseUrl }}/abc' });111 expect(result).to.be.true;112 });113 it('should throw validation error with incorrect data format', function () {114 expect(function () {115 taskOptionValidator.validateContextSkipped(testSchema1, { repo : 'abc' });116 }).to.throw(Error, 'data.repo should match format "uri"');117 });118 it('should throw validation error with task option not rendered', function () {119 expect(function () {120 taskOptionValidator.validateContextSkipped(testSchema1,121 { repo: '{{ option.installScriptUrl }}'});122 }).to.throw(Error, 'data.repo should match format "uri"');123 });124 });...

Full Screen

Full Screen

backup.js

Source:backup.js Github

copy

Full Screen

...21 /**22 * 获取备份列表23 */24 getBackupList: function (absDir) {25 return fs.readdirAsync(`${absDir}/${backupDir}`);26 },27 /**28 * 获取备份文件列表29 */30 getBackupFileList: function (absBackupDir) {31 return fs.readdirAsync(absBackupDir);32 },33 /**34 * 执行恢复(到待发布模式)35 */36 restore: function (absFilePath, absBackupPath) {37 var { dir, base } = path.parse(absFilePath),38 absDeployDir = `${dir}/${deployDir}`,39 absDeployFilePath = `${absDeployDir}/${base}`;40 return fs.ensureDirAsync(absDeployDir)41 .then(() => fs.copyAsync(absBackupPath, absDeployFilePath, {42 clobber: true43 }));44 },45 /**46 * 清理备份(文件已不存在,删除备份)47 *48 * @param absPath 将会清理这个路径下的备份目录49 * @returns {Promise.<*>}50 */51 clean: function (absPath) {52 var absBackupDir = `${absPath}/${backupDir}`;53 return Promise54 .all([55 fs.readdirAsync(absPath).catchReturn([]),56 fs.readdirAsync(absBackupDir).catchReturn([])57 ])58 .then(([files, backupDirs]) => backupDirs.filter(backupDir => !files.includes(backupDir)))59 .then(backupDirs => Promise.all(60 backupDirs.map(backupDir => {61 return fs.removeAsync(`${absBackupDir}/${backupDir}`)62 .then(() => logger.info('[清理: 备份目录]', `${absBackupDir}/${backupDir}`));63 })64 ));65 },66 /**67 * 清理备份文件(备份数大于MaxSize)68 *69 * @param absPath 清理该目录下的备份文件70 * @returns {Promise.<*>}71 */72 cleanFile: function (absPath) {73 var absBackupDir = `${absPath}/${backupDir}`;74 return fs.readdirAsync(absBackupDir)75 .catchReturn(Promise.resolve([]))76 .then(backupDirs => Promise.all(77 backupDirs.map(dir => this._cleanFile(`${absBackupDir}/${dir}`))78 ));79 },80 _cleanFile: function (absBackupDirPath) {81 return fs.readdirAsync(absBackupDirPath)82 .then(files => files.sort().reverse().slice(backupMaxSize))83 .then(files => {84 if (!files.length) {85 return Promise.resolve();86 }87 return Promise.all(88 files.map(file => {89 const absBackupFilePath = `${absBackupDirPath}/${file}`;90 return fs.removeAsync(absBackupFilePath)91 .then(() => logger.info('[清理: 备份文件]', absBackupFilePath));92 })93 );94 });95 },...

Full Screen

Full Screen

file-loader-spec.js

Source:file-loader-spec.js Github

copy

Full Screen

1// Copyright 2015, EMC, Inc.2'use strict';3describe('FileLoader', function () {4 var FileLoader;5 var fs;6 helper.before();7 before(function () {8 FileLoader = helper.injector.get('FileLoader');9 fs = helper.injector.get('fs');10 this.subject = new FileLoader();11 sinon.stub(fs, 'writeFileAsync');12 sinon.stub(fs, 'readFileAsync');13 sinon.stub(fs, 'readdirAsync');14 sinon.stub(fs, 'statAsync');15 });16 beforeEach(function() {17 fs.writeFileAsync.reset();18 fs.readFileAsync.reset();19 fs.readdirAsync.reset();20 fs.statAsync.reset();21 });22 helper.after(function () {23 fs.writeFileAsync.restore();24 fs.readFileAsync.restore();25 fs.readdirAsync.restore();26 fs.statAsync.restore();27 });28 describe('put', function () {29 it('should write the contents to the specified file', function () {30 fs.writeFileAsync.resolves('put');31 return this.subject.put('filename', 'contents').then(function (contents) {32 fs.writeFileAsync.should.have.been.calledWith('filename', 'contents');33 contents.should.equal('put');34 });35 });36 });37 describe('get', function () {38 it('should get the contents for the specified file', function () {39 fs.readFileAsync.resolves('get');40 return this.subject.get('filename').then(function (contents) {41 fs.readFileAsync.should.have.been.calledWith('filename');42 contents.should.equal('get');43 });44 });45 });46 describe('getAll', function () {47 it(48 'should return a promise fulfilled with the file basename to contents in an object',49 function () {50 fs.readFileAsync.resolves('getAll');51 fs.readdirAsync.resolves(['foo.txt']);52 fs.statAsync.resolves({ isDirectory: function() { return false; } });53 return this.subject.getAll('/tmp').then(function (files) {54 fs.readdirAsync.should.have.been.calledWith('/tmp');55 files['foo.txt'].should.have.property('path')56 .and.to.equal('/tmp/foo.txt');57 files['foo.txt'].should.have.property('contents')58 .and.to.equal('getAll');59 });60 }61 );62 it(63 'should skip directories when recursive is disabled',64 function () {65 fs.readFileAsync.resolves('getAll');66 fs.readdirAsync.resolves(['foo']);67 fs.statAsync.resolves({ isDirectory: function() { return true; } });68 return this.subject.getAll('/tmp').then(function () {69 fs.readdirAsync.should.have.been.calledWith('/tmp');70 fs.readFileAsync.should.not.have.been.called;71 });72 }73 );74 it(75 'should not skip directories when recursive is enabled',76 function () {77 fs.readFileAsync.resolves('getAll');78 fs.readdirAsync.withArgs('/tmp').resolves(['foo']);79 fs.readdirAsync.withArgs('/tmp/foo').resolves([]);80 fs.statAsync.resolves({ isDirectory: function() { return true; } });81 return this.subject.getAll('/tmp', true).then(function () {82 fs.readdirAsync.should.have.been.calledWith('/tmp');83 fs.readdirAsync.should.have.been.calledWith('/tmp/foo');84 fs.readFileAsync.should.not.have.been.called;85 });86 }87 );88 });...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

1'use strict';2const fs = require('fs');3const utils = require('../lib/utils');4describe('utils', () => {5 const sandbox = sinon.sandbox.create();6 afterEach(() => sandbox.restore());7 describe('matchesFormats', () => {8 it('should return `true` if the formats option contain passed file format', () => {9 assert.isTrue(utils.matchesFormats('some/path/file.js', ['.js']));10 });11 it('should return `false` if the formats option does not contain passed file format', () => {12 assert.isFalse(utils.matchesFormats('some/path/file.js', ['.txt']));13 });14 });15 describe('isFile', () => {16 beforeEach(() => {17 sandbox.stub(fs, 'statAsync');18 });19 it('should return `true` if the passed path is file', () => {20 fs.statAsync.resolves({isFile: () => true});21 return assert.becomes(utils.isFile('some/path/file.js'), true);22 });23 it('should return `false` if the passed path is directory', () => {24 fs.statAsync.resolves({isFile: () => false});25 return assert.becomes(utils.isFile('some/path/dir'), false);26 });27 });28 describe('getFilePaths', () => {29 const createStatStub = (paths, opts) => {30 paths.forEach((path) => {31 fs.statAsync.withArgs(path).resolves({isFile: () => opts.isFile});32 });33 };34 const createFiles = (...paths) => createStatStub(paths, {isFile: true});35 const createDirs = (...paths) => createStatStub(paths, {isFile: false});36 beforeEach(() => {37 sandbox.stub(fs, 'statAsync');38 sandbox.stub(fs, 'readdirAsync');39 });40 it('should return file if argument is a file', () => {41 createFiles('file.js');42 return assert.becomes(utils.getFilePaths('file.js'), ['file.js']);43 });44 it('should return empty array if argument is an empty directory', () => {45 createDirs(false, 'dir');46 fs.readdirAsync.withArgs('dir').resolves([]);47 return assert.becomes(utils.getFilePaths('dir'), []);48 });49 it('should return only files from file system', () => {50 createDirs('root', 'root/subdir');51 createFiles('root/file.js', 'root/subdir/file2.txt', 'root/subdir/file3.txt');52 fs.readdirAsync.withArgs('root').resolves(['file.js', 'subdir']);53 fs.readdirAsync.withArgs('root/subdir').resolves(['file2.txt', 'file3.txt']);54 return assert.becomes(utils.getFilePaths('root'), ['root/file.js', 'root/subdir/file2.txt', 'root/subdir/file3.txt']);55 });56 it('should throw an error if directory is not acceptable', () => {57 createDirs('root');58 fs.readdirAsync.rejects('no-rights');59 return assert.isRejected(utils.getFilePaths('root'), /no-rights/);60 });61 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('fs.readdirAsync', () => {2 it('lists files in a directory', () => {3 cy.task('fs.readdirAsync', 'cypress/fixtures')4 .then(files => {5 expect(files).to.be.an('array')6 expect(files).to.include('example.json')7 })8 })9})10describe('fs.readdirAsync', () => {11 it('lists files in a directory', () => {12 cy.task('fs.readdirAsync', 'cypress/fixtures')13 .then(files => {14 expect(files).to.be.an('array')15 expect(files).to.include('example.json')16 })17 })18})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Cypress Promise', () => {2 it('test', () => {3 cy.readFile('cypress.json').then((data) => {4 console.log(data)5 })6 })7})8{9}

Full Screen

Using AI Code Generation

copy

Full Screen

1const fs = require('fs');2const util = require('util');3const readdirAsync = util.promisify(fs.readdir);4const path = require('path');5const pathToDir = path.resolve('cypress/integration');6const pathToScreenshots = path.resolve('cypress/screenshots');7const pathToVideos = path.resolve('cypress/videos');8const fs = require('fs');9const util = require('util');10const readdirAsync = util.promisify(fs.readdir);11const path = require('path');12const pathToDir = path.resolve('cypress/integration');13const pathToScreenshots = path.resolve('cypress/screenshots');14const pathToVideos = path.resolve('cypress/videos');15const fs = require('fs');16const util = require('util');17const readdirAsync = util.promisify(fs.readdir);18const path = require('path');19const pathToDir = path.resolve('cypress/integration');20const pathToScreenshots = path.resolve('cypress/screenshots');21const pathToVideos = path.resolve('cypress/videos');22const fs = require('fs');23const util = require('util');24const readdirAsync = util.promisify(fs.readdir);25const path = require('path');26const pathToDir = path.resolve('cypress/integration');27const pathToScreenshots = path.resolve('cypress/screenshots');28const pathToVideos = path.resolve('cypress/videos');29const fs = require('fs');30const util = require('util');31const readdirAsync = util.promisify(fs.readdir);32const path = require('path');33const pathToDir = path.resolve('cypress/integration');34const pathToScreenshots = path.resolve('cypress/screenshots');35const pathToVideos = path.resolve('cypress/videos');36const fs = require('fs');37const util = require('util');38const readdirAsync = util.promisify(fs.readdir);39const path = require('path');40const pathToDir = path.resolve('cypress/integration');41const pathToScreenshots = path.resolve('cypress/screenshots');42const pathToVideos = path.resolve('cypress/videos');43const fs = require('fs');44const util = require('util

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.fs.readdirAsync("cypress/fixtures/").then((files) => {2 files.forEach((file) => {3 cy.log(file);4 });5});6cy.fs.readFileAsync("cypress/fixtures/fixture.json").then((contents) => {7 cy.log(contents);8});9 .writeFileAsync("cypress/fixtures/fixture.json", "{key:value}")10 .then(() => {11 cy.log("Write operation completed");12 });13 .appendFileAsync("cypress/fixtures/fixture.json", "{key:value}")14 .then(() => {15 cy.log("Append operation completed");16 });17 .copyFileAsync("cypress/fixtures/fixture.json", "cypress/fixtures/fixture1.json")18 .then(() => {19 cy.log("Copy operation completed");20 });21 .renameAsync(22 .then(() => {23 cy.log("Rename operation completed");24 });25cy.fs.unlinkAsync("cypress/fixtures/fixture.json").then(() => {26 cy.log("Delete operation completed");27});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { readdirAsync } = require('fs')2readdirAsync('./path/to/dir').then((files) => {3})4const { readdirSync } = require('fs')5const files = readdirSync('./path/to/dir')6const { readdirSyncWithFileTypes } = require('fs')7const files = readdirSyncWithFileTypes('./path/to/dir')8const { readlink } = require('fs')9readlink('./path/to/link').then((linkString) => {10})11const { readlinkSync } = require('fs')12const linkString = readlinkSync('./path/to/link')13const { realpath } = require('fs')

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