How to use fs.mkdir method in Cypress

Best JavaScript code snippet using cypress

Run Cypress automation tests on LambdaTest cloud grid

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

project.spec.js

Source: project.spec.js Github

copy
1// Test Modules
2import { expect, assert } from          'chai';
3import simple, { mock } from            'simple-mock';
4
5// System Modules
6import yargs from                       'yargs';
7import { default as promptly } from     'promptly';
8import fs from                          'fs';
9import util from                        'util';
10import { bold, green } from             'chalk';
11import $LogProvider from                'angie-log';
12
13// Angie Modules
14const TEST_ENV =                        global.TEST_ENV || 'src',
15    project =                           require(`../../../../${TEST_ENV}/util/scaffold/project`),
16    $$ProjectCreationError =            require(`../../../../${TEST_ENV}/services/$Exceptions`).$$ProjectCreationError,
17    p = process;
18
19describe('$$createProject', function() {
20    let noop = () => null;
21
22    beforeEach(function() {
23        yargs([]);
24        mock(fs, 'mkdirSync', noop);
25        mock(fs, 'readFileSync', noop);
26        mock(util, 'format', () => 'test');
27        mock(fs, 'writeFileSync', noop);
28        mock($LogProvider, 'info', noop);
29        mock(p, 'exit', noop);
30        mock(promptly, 'confirm', function(_, fn) {
31            fn(null, true);
32        });
33        mock(promptly, 'prompt', function(_, obj = {}, fn) {
34            fn(null, true);
35        });
36    });
37    afterEach(() => simple.restore());
38    it('test $$createProject called without a name', function() {
39        expect(project).to.throw($$ProjectCreationError);
40    });
41    it('test $$createProject called without a name', function() {
42        expect(project.bind(null, {
43            name: '111'
44        })).to.throw($$ProjectCreationError);
45        expect(project.bind(null, {
46            name: '#][]\\$%'
47        })).to.throw($$ProjectCreationError);
48    });
49    it('test $$createProject scaffolding error', function() {
50        fs.mkdirSync.returnWith(new Error());
51        expect(project).to.throw($$ProjectCreationError);
52    });
53    it('test successful project creation with directory', function() {
54        project({
55            name: 'test',
56            dir: 'test/'
57        });
58        expect(fs.mkdirSync.calls[0].args[0]).to.eq('test');
59        expect(fs.mkdirSync.calls[1].args[0]).to.eq('test/src');
60        expect(fs.mkdirSync.calls[2].args[0]).to.eq('test/src/constants');
61        expect(fs.mkdirSync.calls[3].args[0]).to.eq('test/src/configs');
62        expect(fs.mkdirSync.calls[4].args[0]).to.eq('test/src/services');
63        expect(fs.mkdirSync.calls[5].args[0]).to.eq('test/src/factories');
64        expect(fs.mkdirSync.calls[6].args[0]).to.eq('test/src/controllers');
65        expect(fs.mkdirSync.calls[7].args[0]).to.eq('test/src/directives');
66        expect(fs.mkdirSync.calls[8].args[0]).to.eq('test/test');
67        expect(fs.mkdirSync.calls[9].args[0]).to.eq('test/static');
68        expect(fs.mkdirSync.calls[10].args[0]).to.eq('test/templates');
69        expect(promptly.confirm.calls[0].args[0]).to.eq(
70            `${bold(green('Do you want Angie to cache static assets?'))} :`
71        );
72        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
73            fs.readFileSync(
74                '../../../../src/templates/json/AngieFile.template.json'
75            ),
76            'test',
77            'test',
78            true
79        ]);
80        expect(util.format.calls[0].args[4].val).to.eq(true);
81        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
82            'test/AngieFile.json', 'test', 'utf8'
83        ]);
84        expect(
85            $LogProvider.info.calls[0].args[0]
86        ).to.eq('Project successfully created');
87        expect(p.exit.calls[0].args[0]).to.eq(0);
88    });
89    it('test successful project creation with -n argument', function() {
90        yargs([ '-n', 'test' ]);
91        project({
92            name: 'test1',
93            dir: 'test/'
94        });
95        expect(fs.mkdirSync.calls[0].args[0]).to.eq('test');
96        expect(fs.mkdirSync.calls[1].args[0]).to.eq('test/src');
97        expect(fs.mkdirSync.calls[2].args[0]).to.eq('test/src/constants');
98        expect(fs.mkdirSync.calls[3].args[0]).to.eq('test/src/configs');
99        expect(fs.mkdirSync.calls[4].args[0]).to.eq('test/src/services');
100        expect(fs.mkdirSync.calls[5].args[0]).to.eq('test/src/factories');
101        expect(fs.mkdirSync.calls[6].args[0]).to.eq('test/src/controllers');
102        expect(fs.mkdirSync.calls[7].args[0]).to.eq('test/src/directives');
103        expect(fs.mkdirSync.calls[8].args[0]).to.eq('test/test');
104        expect(fs.mkdirSync.calls[9].args[0]).to.eq('test/static');
105        expect(fs.mkdirSync.calls[10].args[0]).to.eq('test/templates');
106        expect(promptly.confirm.calls[0].args[0]).to.eq(
107            `${bold(green('Do you want Angie to cache static assets?'))} :`
108        );
109        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
110            fs.readFileSync(
111                '../../../../src/templates/json/AngieFile.template.json'
112            ),
113            'test',
114            'test',
115            true
116        ]);
117        expect(util.format.calls[0].args[4].val).to.eq(true);
118        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
119            'test/AngieFile.json', 'test', 'utf8'
120        ]);
121        expect(
122            $LogProvider.info.calls[0].args[0]
123        ).to.eq('Project successfully created');
124        expect(p.exit.calls[0].args[0]).to.eq(0);
125    });
126    it('test successful project creation with --name argument', function() {
127        yargs([ '--name', 'test' ]);
128        project({
129            name: 'test1',
130            dir: 'test/'
131        });
132        expect(fs.mkdirSync.calls[0].args[0]).to.eq('test');
133        expect(fs.mkdirSync.calls[1].args[0]).to.eq('test/src');
134        expect(fs.mkdirSync.calls[2].args[0]).to.eq('test/src/constants');
135        expect(fs.mkdirSync.calls[3].args[0]).to.eq('test/src/configs');
136        expect(fs.mkdirSync.calls[4].args[0]).to.eq('test/src/services');
137        expect(fs.mkdirSync.calls[5].args[0]).to.eq('test/src/factories');
138        expect(fs.mkdirSync.calls[6].args[0]).to.eq('test/src/controllers');
139        expect(fs.mkdirSync.calls[7].args[0]).to.eq('test/src/directives');
140        expect(fs.mkdirSync.calls[8].args[0]).to.eq('test/test');
141        expect(fs.mkdirSync.calls[9].args[0]).to.eq('test/static');
142        expect(fs.mkdirSync.calls[10].args[0]).to.eq('test/templates');
143        expect(promptly.confirm.calls[0].args[0]).to.eq(
144            `${bold(green('Do you want Angie to cache static assets?'))} :`
145        );
146        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
147            fs.readFileSync(
148                '../../../../src/templates/json/AngieFile.template.json'
149            ),
150            'test',
151            'test',
152            true
153        ]);
154        expect(util.format.calls[0].args[4].val).to.eq(true);
155        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
156            'test/AngieFile.json', 'test', 'utf8'
157        ]);
158        expect(
159            $LogProvider.info.calls[0].args[0]
160        ).to.eq('Project successfully created');
161        expect(p.exit.calls[0].args[0]).to.eq(0);
162    });
163    it('test successful project creation with directory false confirm', function() {
164        mock(promptly, 'confirm', function(_, fn) {
165            fn(false);
166        });
167        mock(promptly, 'prompt', function(_, obj = {}, fn) {
168            fn(null, false);
169        });
170        project({
171            name: 'test',
172            dir: 'test/'
173        });
174        expect(fs.mkdirSync.calls[0].args[0]).to.eq('test');
175        expect(fs.mkdirSync.calls[1].args[0]).to.eq('test/src');
176        expect(fs.mkdirSync.calls[2].args[0]).to.eq('test/src/constants');
177        expect(fs.mkdirSync.calls[3].args[0]).to.eq('test/src/configs');
178        expect(fs.mkdirSync.calls[4].args[0]).to.eq('test/src/services');
179        expect(fs.mkdirSync.calls[5].args[0]).to.eq('test/src/factories');
180        expect(fs.mkdirSync.calls[6].args[0]).to.eq('test/src/controllers');
181        expect(fs.mkdirSync.calls[7].args[0]).to.eq('test/src/directives');
182        expect(fs.mkdirSync.calls[8].args[0]).to.eq('test/test');
183        expect(fs.mkdirSync.calls[9].args[0]).to.eq('test/static');
184        expect(fs.mkdirSync.calls[10].args[0]).to.eq('test/templates');
185        expect(promptly.confirm.calls[0].args[0]).to.eq(
186            `${bold(green('Do you want Angie to cache static assets?'))} :`
187        );
188        assert(promptly.prompt.called);
189        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
190            fs.readFileSync(
191                '../../../../src/templates/json/AngieFile.template.json'
192            ),
193            'test',
194            'test',
195            false
196        ]);
197        expect(util.format.calls[0].args[4].val).to.eq(false);
198        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
199            'test/AngieFile.json', 'test', 'utf8'
200        ]);
201        expect(
202            $LogProvider.info.calls[0].args[0]
203        ).to.eq('Project successfully created');
204        expect(p.exit.calls[0].args[0]).to.eq(0);
205    });
206    it('test successful project creation with "." directory', function() {
207        project({
208            name: 'test',
209            dir: '.'
210        });
211        expect(fs.mkdirSync.calls[0].args[0]).to.eq('src');
212        expect(fs.mkdirSync.calls[1].args[0]).to.eq('src/constants');
213        expect(fs.mkdirSync.calls[2].args[0]).to.eq('src/configs');
214        expect(fs.mkdirSync.calls[3].args[0]).to.eq('src/services');
215        expect(fs.mkdirSync.calls[4].args[0]).to.eq('src/factories');
216        expect(fs.mkdirSync.calls[5].args[0]).to.eq('src/controllers');
217        expect(fs.mkdirSync.calls[6].args[0]).to.eq('src/directives');
218        expect(fs.mkdirSync.calls[7].args[0]).to.eq('test');
219        expect(fs.mkdirSync.calls[8].args[0]).to.eq('static');
220        expect(fs.mkdirSync.calls[9].args[0]).to.eq('templates');
221        expect(promptly.confirm.calls[0].args[0]).to.eq(
222            `${bold(green('Do you want Angie to cache static assets?'))} :`
223        );
224        assert(promptly.prompt.called);
225        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
226            fs.readFileSync(
227                '../../../../src/templates/json/AngieFile.template.json'
228            ),
229            'test',
230            'test',
231            true
232        ]);
233        expect(util.format.calls[0].args[4].val).to.eq(true);
234        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
235            'AngieFile.json', 'test', 'utf8'
236        ]);
237        expect(
238            $LogProvider.info.calls[0].args[0]
239        ).to.eq('Project successfully created');
240        expect(p.exit.calls[0].args[0]).to.eq(0);
241    });
242    it('test successful project creation with -d', function() {
243        yargs([ '-d', 'test' ]);
244        project({
245            name: 'test',
246            dir: 'test/'
247        });
248        expect(fs.mkdirSync.calls[0].args[0]).to.eq('test');
249        expect(fs.mkdirSync.calls[1].args[0]).to.eq('test/src');
250        expect(fs.mkdirSync.calls[2].args[0]).to.eq('test/src/constants');
251        expect(fs.mkdirSync.calls[3].args[0]).to.eq('test/src/configs');
252        expect(fs.mkdirSync.calls[4].args[0]).to.eq('test/src/services');
253        expect(fs.mkdirSync.calls[5].args[0]).to.eq('test/src/factories');
254        expect(fs.mkdirSync.calls[6].args[0]).to.eq('test/src/controllers');
255        expect(fs.mkdirSync.calls[7].args[0]).to.eq('test/src/directives');
256        expect(fs.mkdirSync.calls[8].args[0]).to.eq('test/test');
257        expect(fs.mkdirSync.calls[9].args[0]).to.eq('test/static');
258        expect(fs.mkdirSync.calls[10].args[0]).to.eq('test/templates');
259        expect(promptly.confirm.calls[0].args[0]).to.eq(
260            `${bold(green('Do you want Angie to cache static assets?'))} :`
261        );
262        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
263            fs.readFileSync(
264                '../../../../src/templates/json/AngieFile.template.json'
265            ),
266            'test',
267            'test',
268            true
269        ]);
270        expect(util.format.calls[0].args[4].val).to.eq(true);
271        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
272            'test/AngieFile.json', 'test', 'utf8'
273        ]);
274        expect(
275            $LogProvider.info.calls[0].args[0]
276        ).to.eq('Project successfully created');
277        expect(p.exit.calls[0].args[0]).to.eq(0);
278    });
279    it('test successful project creation with --dir', function() {
280        yargs([ '--dir', 'test' ]);
281        project({
282            name: 'test',
283            dir: 'test/'
284        });
285        expect(fs.mkdirSync.calls[0].args[0]).to.eq('test');
286        expect(fs.mkdirSync.calls[1].args[0]).to.eq('test/src');
287        expect(fs.mkdirSync.calls[2].args[0]).to.eq('test/src/constants');
288        expect(fs.mkdirSync.calls[3].args[0]).to.eq('test/src/configs');
289        expect(fs.mkdirSync.calls[4].args[0]).to.eq('test/src/services');
290        expect(fs.mkdirSync.calls[5].args[0]).to.eq('test/src/factories');
291        expect(fs.mkdirSync.calls[6].args[0]).to.eq('test/src/controllers');
292        expect(fs.mkdirSync.calls[7].args[0]).to.eq('test/src/directives');
293        expect(fs.mkdirSync.calls[8].args[0]).to.eq('test/test');
294        expect(fs.mkdirSync.calls[9].args[0]).to.eq('test/static');
295        expect(fs.mkdirSync.calls[10].args[0]).to.eq('test/templates');
296        expect(promptly.confirm.calls[0].args[0]).to.eq(
297            `${bold(green('Do you want Angie to cache static assets?'))} :`
298        );
299        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
300            fs.readFileSync(
301                '../../../../src/templates/json/AngieFile.template.json'
302            ),
303            'test',
304            'test',
305            true
306        ]);
307        expect(util.format.calls[0].args[4].val).to.eq(true);
308        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
309            'test/AngieFile.json', 'test', 'utf8'
310        ]);
311        expect(
312            $LogProvider.info.calls[0].args[0]
313        ).to.eq('Project successfully created');
314        expect(p.exit.calls[0].args[0]).to.eq(0);
315    });
316    it('test successful project creation with no directory', function() {
317        const CWD = p.cwd();
318
319        project({
320            name: 'test'
321        });
322        expect(fs.mkdirSync.calls[0].args[0]).to.eq(`${CWD}/test`);
323        expect(fs.mkdirSync.calls[1].args[0]).to.eq(`${CWD}/test/src`);
324        expect(fs.mkdirSync.calls[2].args[0]).to.eq(
325            `${CWD}/test/src/constants`
326        );
327        expect(fs.mkdirSync.calls[3].args[0]).to.eq(
328            `${CWD}/test/src/configs`
329        );
330        expect(fs.mkdirSync.calls[4].args[0]).to.eq(
331            `${CWD}/test/src/services`
332        );
333        expect(fs.mkdirSync.calls[5].args[0]).to.eq(
334            `${CWD}/test/src/factories`
335        );
336        expect(fs.mkdirSync.calls[6].args[0]).to.eq(
337            `${CWD}/test/src/controllers`
338        );
339        expect(fs.mkdirSync.calls[7].args[0]).to.eq(
340            `${CWD}/test/src/directives`
341        );
342        expect(
343            fs.mkdirSync.calls[8].args[0]
344        ).to.eq(`${CWD}/test/test`);
345        expect(
346            fs.mkdirSync.calls[9].args[0]
347        ).to.eq(`${CWD}/test/static`);
348        expect(
349            fs.mkdirSync.calls[10].args[0]
350        ).to.eq(`${CWD}/test/templates`);
351        expect(promptly.confirm.calls[0].args[0]).to.eq(
352            `${bold(green('Do you want Angie to cache static assets?'))} :`
353        );
354        assert(promptly.prompt.called);
355        expect(util.format.calls[0].args.slice(0, 4)).to.deep.eq([
356            fs.readFileSync(
357                '../../../../src/templates/json/AngieFile.template.json'
358            ),
359            'test',
360            'test',
361            true
362        ]);
363        expect(util.format.calls[0].args[4].val).to.eq(true);
364        expect(fs.writeFileSync.calls[0].args).to.deep.eq([
365            `${CWD}/test/AngieFile.json`, 'test', 'utf8'
366        ]);
367        expect(
368            $LogProvider.info.calls[0].args[0]
369        ).to.eq('Project successfully created');
370        expect(p.exit.calls[0].args[0]).to.eq(0);
371    });
372});
Full Screen

resolveCache.js

Source: resolveCache.js Github

copy
1var path = require('path');
2var mout = require('mout');
3var rimraf = require('rimraf');
4var fs = require('graceful-fs');
5var Q = require('q');
6var expect = require('expect.js');
7var mkdirp = require('mkdirp');
8var ResolveCache = require('../../lib/core/ResolveCache');
9var defaultConfig = require('../../lib/config');
10var cmd = require('../../lib/util/cmd');
11var copy = require('../../lib/util/copy');
12var md5 = require('../../lib/util/md5');
13
14describe('ResolveCache', function () {
15    var resolveCache;
16    var testPackage = path.resolve(__dirname, '../assets/package-a');
17    var tempPackage = path.resolve(__dirname, '../assets/temp');
18    var tempPackage2 = path.resolve(__dirname, '../assets/temp2');
19    var cacheDir = path.join(__dirname, '../assets/temp-resolve-cache');
20
21    before(function (next) {
22        // Delete cache folder
23        rimraf.sync(cacheDir);
24
25        // Instantiate resolver cache
26        resolveCache = new ResolveCache(mout.object.deepMixIn(defaultConfig, {
27            storage: {
28                packages: cacheDir
29            }
30        }));
31
32        // Checkout test package version 0.2.0
33        cmd('git', ['checkout', '0.2.0'], { cwd: testPackage })
34        .then(next.bind(next, null), next);
35    });
36
37    beforeEach(function () {
38        // Reset in memory cache for each test
39        resolveCache.reset();
40    });
41
42    after(function () {
43        // Remove cache folder afterwards
44        rimraf.sync(cacheDir);
45    });
46
47    describe('.constructor', function () {
48        beforeEach(function () {
49            // Delete temp folder
50            rimraf.sync(tempPackage);
51        });
52        after(function () {
53            // Delete temp folder
54            rimraf.sync(tempPackage);
55        });
56
57        function initialize(cacheDir) {
58            return new ResolveCache(mout.object.deepMixIn(defaultConfig, {
59                storage: {
60                    packages: cacheDir
61                }
62            }));
63        }
64
65        it('should create the cache folder if it doesn\'t exists', function () {
66            initialize(tempPackage);
67            expect(fs.existsSync(tempPackage)).to.be(true);
68        });
69
70        it('should not error out if the cache folder already exists', function () {
71            mkdirp.sync(tempPackage);
72            initialize(tempPackage);
73        });
74    });
75
76    describe('.store', function () {
77        var oldFsRename = fs.rename;
78
79        beforeEach(function (next) {
80            // Restore oldFsRename
81            fs.rename = oldFsRename;
82
83            // Create a fresh copy of the test package into temp
84            rimraf.sync(tempPackage);
85            copy.copyDir(testPackage, tempPackage, { ignore: ['.git'] })
86            .then(next.bind(next, null), next);
87        });
88
89        it('should move the canonical dir to source-md5/version/ folder if package meta has a version', function (next) {
90            resolveCache.store(tempPackage, {
91                name: 'foo',
92                version: '1.0.0',
93                _source: 'foo',
94                _target: '*'
95            })
96            .then(function (dir) {
97                expect(dir).to.equal(path.join(cacheDir, md5('foo'), '1.0.0'));
98                expect(fs.existsSync(dir)).to.be(true);
99                expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true);
100                expect(fs.existsSync(tempPackage)).to.be(false);
101
102                next();
103            })
104            .done();
105        });
106
107        it('should move the canonical dir to source-md5/target/ folder if package meta has no version', function (next) {
108            resolveCache.store(tempPackage, {
109                name: 'foo',
110                _source: 'foo',
111                _target: 'some-branch'
112            })
113            .then(function (dir) {
114                expect(dir).to.equal(path.join(cacheDir, md5('foo'), 'some-branch'));
115                expect(fs.existsSync(dir)).to.be(true);
116                expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true);
117                expect(fs.existsSync(tempPackage)).to.be(false);
118
119                next();
120            })
121            .done();
122        });
123
124        it('should move the canonical dir to source-md5/_wildcard/ folder if package meta has no version and target is *', function (next) {
125            resolveCache.store(tempPackage, {
126                name: 'foo',
127                _source: 'foo',
128                _target: '*'
129            })
130            .then(function (dir) {
131                expect(dir).to.equal(path.join(cacheDir, md5('foo'), '_wildcard'));
132                expect(fs.existsSync(dir)).to.be(true);
133                expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true);
134                expect(fs.existsSync(tempPackage)).to.be(false);
135
136                next();
137            })
138            .done();
139        });
140
141        it('should overwrite if the exact same package source/version exists', function (next) {
142            var cachePkgDir = path.join(cacheDir, md5('foo'), '1.0.0-rc.blehhh');
143
144            mkdirp.sync(cachePkgDir);
145            fs.writeFileSync(path.join(cachePkgDir, '_bleh'), 'w00t');
146
147            resolveCache.store(tempPackage, {
148                name: 'foo',
149                version: '1.0.0-rc.blehhh',
150                _source: 'foo',
151                _target: '*'
152            })
153            .then(function (dir) {
154                expect(dir).to.equal(cachePkgDir);
155                expect(fs.existsSync(dir)).to.be(true);
156                expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true);
157                expect(fs.existsSync(tempPackage)).to.be(false);
158                expect(fs.existsSync(path.join(cachePkgDir, '_bleh'))).to.be(false);
159
160                next();
161            })
162            .done();
163        });
164
165        it('should read the package meta if not present', function (next) {
166            var pkgMeta = path.join(tempPackage, '.bower.json');
167
168            // Copy bower.json to .bower.json and add some props
169            copy.copyFile(path.join(tempPackage, 'component.json'), pkgMeta)
170            .then(function () {
171                return Q.nfcall(fs.readFile, pkgMeta)
172                .then(function (contents) {
173                    var json = JSON.parse(contents.toString());
174
175                    json._target = '~0.2.0';
176                    json._source = 'git://github.com/bower/test-package.git';
177
178                    return Q.nfcall(fs.writeFile, pkgMeta, JSON.stringify(json, null, '  '));
179                });
180            })
181            // Store as usual
182            .then(function () {
183                return resolveCache.store(tempPackage);
184            })
185            .then(function (dir) {
186                expect(dir).to.equal(path.join(cacheDir, md5('git://github.com/bower/test-package.git'), '0.2.0'));
187                expect(fs.existsSync(dir)).to.be(true);
188                expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true);
189                expect(fs.existsSync(tempPackage)).to.be(false);
190
191                next();
192            })
193            .done();
194        });
195
196        it('should error out when reading the package meta if the file does not exist', function (next) {
197            resolveCache.store(tempPackage)
198            .then(function () {
199                next(new Error('Should have failed'));
200            }, function (err) {
201                expect(err).to.be.an(Error);
202                expect(err.code).to.equal('ENOENT');
203                expect(err.message).to.contain(path.join(tempPackage, '.bower.json'));
204
205                next();
206            })
207            .done();
208        });
209
210        it('should error out when reading an invalid package meta', function (next) {
211            var pkgMeta = path.join(tempPackage, '.bower.json');
212
213            return Q.nfcall(fs.writeFile, pkgMeta, 'w00t')
214            .then(function () {
215                return resolveCache.store(tempPackage)
216                .then(function () {
217                    next(new Error('Should have failed'));
218                }, function (err) {
219                    expect(err).to.be.an(Error);
220                    expect(err.code).to.equal('EMALFORMED');
221                    expect(err.message).to.contain(path.join(tempPackage, '.bower.json'));
222
223                    next();
224                });
225            })
226            .done();
227        });
228
229        it('should move the canonical dir, even if it is in a different drive', function (next) {
230            var hittedMock = false;
231
232            fs.rename = function (src, dest, cb) {
233                hittedMock = true;
234
235                setTimeout(function () {
236                    var err = new Error();
237                    err.code = 'EXDEV';
238                    cb(err);
239                }, 10);
240            };
241
242            resolveCache.store(tempPackage, {
243                name: 'foo',
244                _source: 'foo',
245                _target: 'some-branch'
246            })
247            .then(function (dir) {
248                // Ensure mock was called
249                expect(hittedMock).to.be(true);
250
251                expect(dir).to.equal(path.join(cacheDir, md5('foo'), 'some-branch'));
252                expect(fs.existsSync(dir)).to.be(true);
253                expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true);
254                expect(fs.existsSync(tempPackage)).to.be(false);
255
256                next();
257            })
258            .done();
259        });
260
261        it('should update the in-memory cache', function (next) {
262            // Feed the cache
263            resolveCache.versions('test-in-memory')
264            // Copy temp package to temp package  2
265            .then(function () {
266                return copy.copyDir(tempPackage, tempPackage2, { ignore: ['.git'] });
267            })
268            // Store the two packages
269            .then(function () {
270                return resolveCache.store(tempPackage, {
271                    name: 'foo',
272                    version: '1.0.0',
273                    _source: 'test-in-memory',
274                    _target: '*'
275                });
276            })
277            .then(function () {
278                return resolveCache.store(tempPackage2, {
279                    name: 'foo',
280                    version: '1.0.1',
281                    _source: 'test-in-memory',
282                    _target: '*'
283                });
284            })
285            // Cache should have been updated
286            .then(function () {
287                return resolveCache.versions('test-in-memory')
288                .then(function (versions) {
289                    expect(versions).to.eql(['1.0.1', '1.0.0']);
290
291                    next();
292                });
293            })
294            .done();
295        });
296
297        it('should url encode target when storing to the fs', function (next) {
298            resolveCache.store(tempPackage, {
299                name: 'foo',
300                _source: 'foo',
301                _target: 'foo/bar'
302            })
303            .then(function (dir) {
304                expect(dir).to.equal(path.join(cacheDir, md5('foo'), 'foo%2Fbar'));
305                expect(fs.existsSync(dir)).to.be(true);
306                expect(fs.existsSync(path.join(dir, 'baz'))).to.be(true);
307                expect(fs.existsSync(tempPackage)).to.be(false);
308
309                next();
310            })
311            .done();
312        });
313    });
314
315    describe('.versions', function () {
316        it('should resolve to an array', function (next) {
317            resolveCache.versions(String(Math.random()))
318            .then(function (versions) {
319                expect(versions).to.be.an('array');
320                next();
321            })
322            .done();
323        });
324
325        it('should ignore non-semver folders of the source', function (next) {
326            var source = String(Math.random());
327            var sourceId = md5(source);
328            var sourceDir = path.join(cacheDir, sourceId);
329
330            // Create some versions
331            fs.mkdirSync(sourceDir);
332            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
333            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
334            fs.mkdirSync(path.join(sourceDir, 'foo'));
335
336            resolveCache.versions(source)
337            .then(function (versions) {
338                expect(versions).to.not.contain('foo');
339                expect(versions).to.contain('0.0.1');
340                expect(versions).to.contain('0.1.0');
341                next();
342            })
343            .done();
344        });
345
346        it('should order the versions', function (next) {
347            var source = String(Math.random());
348            var sourceId = md5(source);
349            var sourceDir = path.join(cacheDir, sourceId);
350
351            // Create some versions
352            fs.mkdirSync(sourceDir);
353            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
354            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
355            fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.1'));
356
357            resolveCache.versions(source)
358            .then(function (versions) {
359                expect(versions).to.eql(['0.1.0', '0.1.0-rc.1', '0.0.1']);
360                next();
361            })
362            .done();
363        });
364
365        it('should cache versions to speed-up subsequent calls', function (next) {
366            var source = String(Math.random());
367            var sourceId = md5(source);
368            var sourceDir = path.join(cacheDir, sourceId);
369
370            // Create some versions
371            fs.mkdirSync(sourceDir);
372            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
373
374            resolveCache.versions(source)
375            .then(function () {
376                // Remove folder
377                rimraf.sync(sourceDir);
378
379                return resolveCache.versions(source);
380            })
381            .then(function (versions) {
382                expect(versions).to.eql(['0.0.1']);
383                next();
384            })
385            .done();
386        });
387    });
388
389    describe('.retrieve', function () {
390        it('should resolve to empty if there are no packages for the requested source', function (next) {
391            resolveCache.retrieve(String(Math.random()))
392            .spread(function () {
393                expect(arguments.length).to.equal(0);
394                next();
395            })
396            .done();
397        });
398
399        it('should resolve to empty if there are no suitable packages for the requested target', function (next) {
400            var source = String(Math.random());
401            var sourceId = md5(source);
402            var sourceDir = path.join(cacheDir, sourceId);
403
404            // Create some versions
405            fs.mkdirSync(sourceDir);
406            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
407            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
408            fs.mkdirSync(path.join(sourceDir, '0.1.9'));
409            fs.mkdirSync(path.join(sourceDir, '0.2.0'));
410
411            resolveCache.retrieve(source, '~0.3.0')
412            .spread(function () {
413                expect(arguments.length).to.equal(0);
414
415                return resolveCache.retrieve(source, 'some-branch');
416            })
417            .spread(function () {
418                expect(arguments.length).to.equal(0);
419
420                next();
421            })
422            .done();
423        });
424
425        it('should remove invalid packages from the cache if their package meta is missing or invalid', function (next) {
426            var source = String(Math.random());
427            var sourceId = md5(source);
428            var sourceDir = path.join(cacheDir, sourceId);
429
430            // Create some versions
431            fs.mkdirSync(sourceDir);
432            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
433            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
434            fs.mkdirSync(path.join(sourceDir, '0.1.9'));
435            fs.mkdirSync(path.join(sourceDir, '0.2.0'));
436
437            // Create an invalid package meta
438            fs.writeFileSync(path.join(sourceDir, '0.2.0', '.bower.json'), 'w00t');
439
440            resolveCache.retrieve(source, '~0.1.0')
441            .spread(function () {
442                var dirs = fs.readdirSync(sourceDir);
443
444                expect(arguments.length).to.equal(0);
445                expect(dirs).to.contain('0.0.1');
446                expect(dirs).to.contain('0.2.0');
447                next();
448            })
449            .done();
450        });
451
452        it('should resolve to the highest package that matches a range target, ignoring pre-releases', function (next) {
453            var source = String(Math.random());
454            var sourceId = md5(source);
455            var sourceDir = path.join(cacheDir, sourceId);
456            var json = { name: 'foo' };
457
458            // Create some versions
459            fs.mkdirSync(sourceDir);
460
461            json.version = '0.0.1';
462            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
463            fs.writeFileSync(path.join(sourceDir, '0.0.1', '.bower.json'), JSON.stringify(json, null, '  '));
464
465            json.version = '0.1.0';
466            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
467            fs.writeFileSync(path.join(sourceDir, '0.1.0', '.bower.json'), JSON.stringify(json, null, '  '));
468
469            json.version = '0.1.0-rc.1';
470            fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.1'));
471            fs.writeFileSync(path.join(sourceDir, '0.1.0-rc.1', '.bower.json'), JSON.stringify(json, null, '  '));
472
473            json.version = '0.1.9';
474            fs.mkdirSync(path.join(sourceDir, '0.1.9'));
475            fs.writeFileSync(path.join(sourceDir, '0.1.9', '.bower.json'), JSON.stringify(json, null, '  '));
476
477            json.version = '0.2.0';
478            fs.mkdirSync(path.join(sourceDir, '0.2.0'));
479            fs.writeFileSync(path.join(sourceDir, '0.2.0', '.bower.json'), JSON.stringify(json, null, '  '));
480
481            resolveCache.retrieve(source, '~0.1.0')
482            .spread(function (canonicalDir, pkgMeta) {
483                expect(pkgMeta).to.be.an('object');
484                expect(pkgMeta.version).to.equal('0.1.9');
485                expect(canonicalDir).to.equal(path.join(sourceDir, '0.1.9'));
486
487                return resolveCache.retrieve(source, '*');
488            })
489            .spread(function (canonicalDir, pkgMeta) {
490                expect(pkgMeta).to.be.an('object');
491                expect(pkgMeta.version).to.equal('0.2.0');
492                expect(canonicalDir).to.equal(path.join(sourceDir, '0.2.0'));
493
494                next();
495            })
496            .done();
497        });
498
499        it('should resolve to the highest package that matches a range target, not ignoring pre-releases if they are the only versions', function (next) {
500            var source = String(Math.random());
501            var sourceId = md5(source);
502            var sourceDir = path.join(cacheDir, sourceId);
503            var json = { name: 'foo' };
504
505            // Create some versions
506            fs.mkdirSync(sourceDir);
507
508            json.version = '0.1.0-rc.1';
509            fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.1'));
510            fs.writeFileSync(path.join(sourceDir, '0.1.0-rc.1', '.bower.json'), JSON.stringify(json, null, '  '));
511
512            json.version = '0.1.0-rc.2';
513            fs.mkdirSync(path.join(sourceDir, '0.1.0-rc.2'));
514            fs.writeFileSync(path.join(sourceDir, '0.1.0-rc.2', '.bower.json'), JSON.stringify(json, null, '  '));
515
516            resolveCache.retrieve(source, '~0.1.0')
517            .spread(function (canonicalDir, pkgMeta) {
518                expect(pkgMeta).to.be.an('object');
519                expect(pkgMeta.version).to.equal('0.1.0-rc.2');
520                expect(canonicalDir).to.equal(path.join(sourceDir, '0.1.0-rc.2'));
521
522                next();
523            })
524            .done();
525        });
526
527        it('should resolve to exact match (including build metadata) if available', function (next) {
528            var source = String(Math.random());
529            var sourceId = md5(source);
530            var sourceDir = path.join(cacheDir, sourceId);
531            var json = { name: 'foo' };
532
533            // Create some versions
534            fs.mkdirSync(sourceDir);
535
536            json.version = '0.1.0';
537            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
538            fs.writeFileSync(path.join(sourceDir, '0.1.0', '.bower.json'), JSON.stringify(json, null, '  '));
539
540            json.version = '0.1.0+build.4';
541            fs.mkdirSync(path.join(sourceDir, '0.1.0+build.4'));
542            fs.writeFileSync(path.join(sourceDir, '0.1.0+build.4', '.bower.json'), JSON.stringify(json, null, '  '));
543
544            json.version = '0.1.0+build.5';
545            fs.mkdirSync(path.join(sourceDir, '0.1.0+build.5'));
546            fs.writeFileSync(path.join(sourceDir, '0.1.0+build.5', '.bower.json'), JSON.stringify(json, null, '  '));
547
548            json.version = '0.1.0+build.6';
549            fs.mkdirSync(path.join(sourceDir, '0.1.0+build.6'));
550            fs.writeFileSync(path.join(sourceDir, '0.1.0+build.6', '.bower.json'), JSON.stringify(json, null, '  '));
551
552            resolveCache.retrieve(source, '0.1.0+build.5')
553            .spread(function (canonicalDir, pkgMeta) {
554                expect(pkgMeta).to.be.an('object');
555                expect(pkgMeta.version).to.equal('0.1.0+build.5');
556                expect(canonicalDir).to.equal(path.join(sourceDir, '0.1.0+build.5'));
557
558                next();
559            })
560            .done();
561        });
562
563        it('should resolve to the _wildcard package if target is * and there are no semver versions', function (next) {
564            var source = String(Math.random());
565            var sourceId = md5(source);
566            var sourceDir = path.join(cacheDir, sourceId);
567            var json = { name: 'foo' };
568
569            // Create some versions
570            fs.mkdirSync(sourceDir);
571
572            fs.mkdirSync(path.join(sourceDir, '_wildcard'));
573            fs.writeFileSync(path.join(sourceDir, '_wildcard', '.bower.json'), JSON.stringify(json, null, '  '));
574
575            resolveCache.retrieve(source, '*')
576            .spread(function (canonicalDir, pkgMeta) {
577                expect(pkgMeta).to.be.an('object');
578                expect(canonicalDir).to.equal(path.join(sourceDir, '_wildcard'));
579
580                next();
581            })
582            .done();
583        });
584
585        it('should resolve to the exact target it\'s not a semver range', function (next) {
586            var source = String(Math.random());
587            var sourceId = md5(source);
588            var sourceDir = path.join(cacheDir, sourceId);
589            var json = { name: 'foo' };
590
591            // Create some versions
592            fs.mkdirSync(sourceDir);
593
594            fs.mkdirSync(path.join(sourceDir, 'some-branch'));
595            fs.writeFileSync(path.join(sourceDir, 'some-branch', '.bower.json'), JSON.stringify(json, null, '  '));
596
597            fs.mkdirSync(path.join(sourceDir, 'other-branch'));
598            fs.writeFileSync(path.join(sourceDir, 'other-branch', '.bower.json'), JSON.stringify(json, null, '  '));
599
600            resolveCache.retrieve(source, 'some-branch')
601            .spread(function (canonicalDir, pkgMeta) {
602                expect(pkgMeta).to.be.an('object');
603                expect(pkgMeta).to.not.have.property('version');
604
605                next();
606            })
607            .done();
608        });
609    });
610
611    describe('.eliminate', function () {
612        beforeEach(function () {
613            mkdirp.sync(cacheDir);
614        });
615
616        it('should delete the source-md5/version folder', function (next) {
617            var source = String(Math.random());
618            var sourceId = md5(source);
619            var sourceDir = path.join(cacheDir, sourceId);
620
621            // Create some versions
622            fs.mkdirSync(sourceDir);
623            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
624            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
625
626            resolveCache.eliminate({
627                name: 'foo',
628                version: '0.0.1',
629                _source: source,
630                _target: '*'
631            })
632            .then(function () {
633                expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(false);
634                expect(fs.existsSync(path.join(sourceDir, '0.1.0'))).to.be(true);
635
636                next();
637            })
638            .done();
639        });
640
641        it('should delete the source-md5/target folder', function (next) {
642            var source = String(Math.random());
643            var sourceId = md5(source);
644            var sourceDir = path.join(cacheDir, sourceId);
645
646            // Create some versions
647            fs.mkdirSync(sourceDir);
648            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
649            fs.mkdirSync(path.join(sourceDir, 'some-branch'));
650
651            resolveCache.eliminate({
652                name: 'foo',
653                _source: source,
654                _target: 'some-branch'
655            })
656            .then(function () {
657                expect(fs.existsSync(path.join(sourceDir, 'some-branch'))).to.be(false);
658                expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(true);
659
660                next();
661            })
662            .done();
663        });
664
665        it('should delete the source-md5/_wildcard folder', function (next) {
666            var source = String(Math.random());
667            var sourceId = md5(source);
668            var sourceDir = path.join(cacheDir, sourceId);
669
670            // Create some versions
671            fs.mkdirSync(sourceDir);
672            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
673            fs.mkdirSync(path.join(sourceDir, '_wildcard'));
674
675            resolveCache.eliminate({
676                name: 'foo',
677                _source: source,
678                _target: '*'
679            })
680            .then(function () {
681                expect(fs.existsSync(path.join(sourceDir, '_wildcard'))).to.be(false);
682                expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(true);
683
684                next();
685            })
686            .done();
687        });
688
689        it('should delete the source-md5 folder if empty', function (next) {
690            var source = String(Math.random());
691            var sourceId = md5(source);
692            var sourceDir = path.join(cacheDir, sourceId);
693
694            // Create some versions
695            fs.mkdirSync(sourceDir);
696            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
697
698            resolveCache.eliminate({
699                name: 'foo',
700                version: '0.0.1',
701                _source: source,
702                _target: '*'
703            })
704            .then(function () {
705                expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(false);
706                expect(fs.existsSync(path.join(sourceDir))).to.be(false);
707
708                next();
709            })
710            .done();
711        });
712
713        it('should remove entry from in memory cache if the source-md5 folder was deleted', function (next) {
714            var source = String(Math.random());
715            var sourceId = md5(source);
716            var sourceDir = path.join(cacheDir, sourceId);
717
718            // Create some versions
719            fs.mkdirSync(sourceDir);
720            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
721
722            // Feed up the cache
723            resolveCache.versions(source)
724            // Eliminate
725            .then(function () {
726                return resolveCache.eliminate({
727                    name: 'foo',
728                    version: '0.0.1',
729                    _source: source,
730                    _target: '*'
731                });
732            })
733            .then(function () {
734                // At this point the parent folder should be deleted
735                // To test against the in-memory cache, we create a folder
736                // manually and request the versions
737                mkdirp.sync(path.join(sourceDir, '0.0.2'));
738
739                resolveCache.versions(source)
740                .then(function (versions) {
741                    expect(versions).to.eql(['0.0.2']);
742
743                    next();
744                });
745            })
746            .done();
747        });
748    });
749
750    describe('.clear', function () {
751        beforeEach(function () {
752            mkdirp.sync(cacheDir);
753        });
754
755        it('should empty the whole cache folder', function (next) {
756            resolveCache.clear()
757            .then(function () {
758                var files;
759
760                expect(fs.existsSync(cacheDir)).to.be(true);
761
762                files = fs.readdirSync(cacheDir);
763                expect(files.length).to.be(0);
764
765                next();
766            })
767            .done();
768        });
769
770        it('should erase the in-memory cache', function (next) {
771            var source = String(Math.random());
772            var sourceId = md5(source);
773            var sourceDir = path.join(cacheDir, sourceId);
774
775            // Create some versions
776            fs.mkdirSync(sourceDir);
777            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
778
779            // Feed the in-memory cache
780            resolveCache.versions(source)
781            // Clear
782            .then(function () {
783                return resolveCache.clear();
784            })
785            .then(function () {
786                // To test against the in-memory cache, we create a folder
787                // manually and request the versions
788                mkdirp.sync(path.join(sourceDir, '0.0.2'));
789
790                resolveCache.versions(source)
791                .then(function (versions) {
792                    expect(versions).to.eql(['0.0.2']);
793
794                    next();
795                });
796            })
797            .done();
798        });
799    });
800
801    describe('.reset', function () {
802        it('should erase the in-memory cache', function (next) {
803            var source = String(Math.random());
804            var sourceId = md5(source);
805            var sourceDir = path.join(cacheDir, sourceId);
806
807            // Create some versions
808            fs.mkdirSync(sourceDir);
809            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
810
811            // Feed the in-memory cache
812            resolveCache.versions(source)
813            .then(function () {
814                // Delete 0.0.1 and create 0.0.2
815                fs.rmdirSync(path.join(sourceDir, '0.0.1'));
816                fs.mkdirSync(path.join(sourceDir, '0.0.2'));
817
818                // Reset cache
819                resolveCache.reset();
820
821                // Get versions
822                return resolveCache.versions(source);
823            })
824            .then(function (versions) {
825                expect(versions).to.eql(['0.0.2']);
826
827                next();
828            })
829            .done();
830        });
831    });
832
833    describe('.list', function () {
834        beforeEach(function () {
835            rimraf.sync(cacheDir);
836            mkdirp.sync(cacheDir);
837        });
838
839        it('should resolve to an empty array if the cache is empty', function (next) {
840            resolveCache.list()
841            .then(function (entries) {
842                expect(entries).to.be.an('array');
843                expect(entries.length).to.be(0);
844
845                next();
846            })
847            .done();
848        });
849
850        it('should resolve to an ordered array of entries (name ASC, release ASC)', function (next) {
851            var source = 'list-package-1';
852            var sourceId = md5(source);
853            var sourceDir = path.join(cacheDir, sourceId);
854
855            var source2 = 'list-package-2';
856            var sourceId2 = md5(source2);
857            var sourceDir2 = path.join(cacheDir, sourceId2);
858
859            var json = {
860                name: 'foo'
861            };
862
863            // Create some versions for different sources
864            fs.mkdirSync(sourceDir);
865            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
866            json.version = '0.0.1';
867            fs.writeFileSync(path.join(sourceDir, '0.0.1', '.bower.json'), JSON.stringify(json, null, '  '));
868
869            fs.mkdirSync(path.join(sourceDir, '0.1.0'));
870            json.version = '0.1.0';
871            fs.writeFileSync(path.join(sourceDir, '0.1.0', '.bower.json'), JSON.stringify(json, null, '  '));
872
873            delete json.version;
874
875            fs.mkdirSync(path.join(sourceDir, 'foo'));
876            json._target = 'foo';
877            fs.writeFileSync(path.join(sourceDir, 'foo', '.bower.json'), JSON.stringify(json, null, '  '));
878
879            fs.mkdirSync(path.join(sourceDir, 'bar'));
880            json._target = 'bar';
881            fs.writeFileSync(path.join(sourceDir, 'bar', '.bower.json'), JSON.stringify(json, null, '  '));
882
883            fs.mkdirSync(path.join(sourceDir, 'aa'));
884            json._target = 'aa';
885            fs.writeFileSync(path.join(sourceDir, 'aa', '.bower.json'), JSON.stringify(json, null, '  '));
886
887            delete json._target;
888
889            fs.mkdirSync(sourceDir2);
890            fs.mkdirSync(path.join(sourceDir2, '0.2.1'));
891            json.version = '0.2.1';
892            fs.writeFileSync(path.join(sourceDir2, '0.2.1', '.bower.json'), JSON.stringify(json, null, '  '));
893
894            fs.mkdirSync(path.join(sourceDir2, '0.2.0'));
895            json.name = 'abc';
896            json.version = '0.2.0';
897            fs.writeFileSync(path.join(sourceDir2, '0.2.0', '.bower.json'), JSON.stringify(json, null, '  '));
898
899            resolveCache.list()
900            .then(function (entries) {
901                var expectedJson;
902                var bowerDir = path.join(__dirname, '../..');
903
904                expect(entries).to.be.an('array');
905
906                expectedJson = fs.readFileSync(path.join(__dirname, '../assets/resolve-cache/list-json-1.json'));
907                expectedJson = expectedJson.toString();
908
909                mout.object.forOwn(entries, function (entry) {
910                    // Trim absolute bower path from json
911                    entry.canonicalDir = entry.canonicalDir.substr(bowerDir.length);
912                    // Convert windows \ paths to /
913                    entry.canonicalDir = entry.canonicalDir.replace(/\\/g, '/');
914                });
915
916                json = JSON.stringify(entries, null, '  ');
917                expect(json).to.equal(expectedJson);
918
919                next();
920            })
921            .done();
922        });
923
924        it('should ignore lurking files where dirs are expected', function (next) {
925            var source = 'list-package-1';
926            var sourceId = md5(source);
927            var sourceDir = path.join(cacheDir, sourceId);
928            var json = {
929                name: 'foo'
930            };
931
932            // Create some versions
933            fs.mkdirSync(sourceDir);
934            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
935            json.version = '0.0.1';
936            fs.writeFileSync(path.join(sourceDir, '0.0.1', '.bower.json'), JSON.stringify(json, null, '  '));
937
938            // Create lurking files
939            fs.writeFileSync(path.join(cacheDir, 'foo'), 'w00t');
940            fs.writeFileSync(path.join(cacheDir, '.DS_Store'), '');
941            fs.writeFileSync(path.join(sourceDir, 'foo'), 'w00t');
942            fs.writeFileSync(path.join(sourceDir, '.DS_Store'), '');
943
944            // It should not error out
945            resolveCache.list()
946            .then(function (entries) {
947                expect(entries).to.be.an('array');
948                expect(entries.length).to.be(1);
949                expect(entries[0].pkgMeta).to.eql(json);
950
951                // Lurking file should have been removed
952                expect(fs.existsSync(path.join(cacheDir, 'foo'))).to.be(false);
953                expect(fs.existsSync(path.join(cacheDir, '.DS_Store'))).to.be(false);
954                expect(fs.existsSync(path.join(sourceDir, 'foo'))).to.be(false);
955                expect(fs.existsSync(path.join(sourceDir, '.DS_Store'))).to.be(false);
956
957                next();
958            })
959            .done();
960
961        });
962
963        it('should delete entries if failed to read package meta', function (next) {
964            var source = 'list-package-1';
965            var sourceId = md5(source);
966            var sourceDir = path.join(cacheDir, sourceId);
967            var json = {
968                name: 'foo'
969            };
970
971            // Create invalid versions
972            fs.mkdirSync(sourceDir);
973            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
974
975            fs.mkdirSync(path.join(sourceDir, '0.0.2'));
976            fs.writeFileSync(path.join(sourceDir, '0.0.2', '.bower.json'), 'w00t');
977
978            // Create valid version
979            fs.mkdirSync(path.join(sourceDir, '0.0.3'));
980            json.version = '0.0.3';
981            fs.writeFileSync(path.join(sourceDir, '0.0.3', '.bower.json'), JSON.stringify(json, null, '  '));
982
983            // It should not error out
984            resolveCache.list()
985            .then(function (entries) {
986                expect(entries).to.be.an('array');
987                expect(entries.length).to.be(1);
988                expect(entries[0].pkgMeta).to.eql(json);
989
990                // Packages with invalid metas should have been removed
991                expect(fs.existsSync(path.join(sourceDir, '0.0.1'))).to.be(false);
992                expect(fs.existsSync(path.join(sourceDir, '0.0.2'))).to.be(false);
993
994                next();
995            })
996            .done();
997        });
998    });
999
1000    describe('#clearRuntimeCache', function () {
1001        it('should clear the in-memory cache for all sources', function (next) {
1002            var source = String(Math.random());
1003            var sourceId = md5(source);
1004            var sourceDir = path.join(cacheDir, sourceId);
1005
1006            var source2 = String(Math.random());
1007            var sourceId2 = md5(source2);
1008            var sourceDir2 = path.join(cacheDir, sourceId2);
1009
1010            // Create some versions
1011            fs.mkdirSync(sourceDir);
1012            fs.mkdirSync(path.join(sourceDir, '0.0.1'));
1013            fs.mkdirSync(sourceDir2);
1014            fs.mkdirSync(path.join(sourceDir2, '0.0.2'));
1015
1016            // Feed the cache
1017            resolveCache.versions(source)
1018            .then(function () {
1019                return resolveCache.versions(source2);
1020            })
1021            .then(function () {
1022                // Create some more
1023                fs.mkdirSync(path.join(sourceDir, '0.0.3'));
1024                fs.mkdirSync(path.join(sourceDir2, '0.0.4'));
1025
1026                // Reset cache
1027                ResolveCache.clearRuntimeCache();
1028            })
1029            .then(function () {
1030                return resolveCache.versions(source)
1031                .then(function (versions) {
1032                    expect(versions).to.eql(['0.0.3', '0.0.1']);
1033
1034                    return resolveCache.versions(source2);
1035                })
1036                .then(function (versions) {
1037                    expect(versions).to.eql(['0.0.4', '0.0.2']);
1038
1039                    next();
1040                });
1041            })
1042            .done();
1043        });
1044    });
1045});
1046
Full Screen

Project.js

Source: Project.js Github

copy
1Ext.define('Command.module.Project', {
2    extend: 'Command.module.Abstract',
3
4    description: 'Utility actions to work a project',
5
6    actions: {
7        create: [
8            "Generate a new project with the recommended structure",
9            ['name', 'p', 'The name of the application to create', 'string', null, 'MyApp']
10        ]
11    },
12    
13    constructor: function() {
14        this.templates = {};
15        
16        this.callParent(arguments);
17    },
18
19    create: function(name) {
20        this.args = {
21            name: name
22        };
23        
24        console.log(this.args);
25        
26        this.createDirectories(name);
27        this.copyFiles(name);
28        
29    },
30    
31    createDirectories: function(name) {
32        var fs   = require('fs'),
33            path = require('path');
34        
35        fs.mkdirSync(name);
36        
37        fs.mkdirSync(path.join(name, 'app'));
38        fs.mkdirSync(path.join(name, 'app', 'model'));
39        fs.mkdirSync(path.join(name, 'app', 'view'));
40        fs.mkdirSync(path.join(name, 'app', 'controller'));
41        fs.mkdirSync(path.join(name, 'app', 'store'));
42        fs.mkdirSync(path.join(name, 'app', 'profile'));
43        
44        fs.mkdirSync(path.join(name, 'deploy'));
45    },
46    
47    template: function(template, destination) {
48        var fs   = require('fs'),
49            path = require('path');
50        
51        template = this.getTemplate(template);
52        
53        console.log(template.apply(this.args));
54        
55        fs.writeFile(path || template, template.apply(this.args));
56    },
57    
58    copyFiles: function(name) {
59        var fs   = require('fs'),
60            path = require('path');
61        
62        this.template('index.html')
63    },
64    
65    getTemplate: function(name) {
66        var templates = this.templates,
67            template = templates[name],
68            filePath;
69
70        if (!template) {
71            filePath = require('path').resolve(this.cli.getCurrentPath(), 'src/module/Project/templates/' + name + '.tpl');
72            templates[name] = template = Ext.create('Ext.XTemplate', this.getModule('fs').read(filePath));
73        }
74
75        return template;
76    }
77});
78
79// this.log("Generate application at " + path + " with namespace: " + namespace);
80// this.info("Generate application at " + path + " with namespace: " + namespace);
81// this.warn("Generate application at " + path + " with namespace: " + namespace);
82// this.error("Generate application at " + path + " with namespace: " + namespace);
Full Screen

directoryTests.js

Source: directoryTests.js Github

copy
1var expect = require('chai').expect
2    should = require('chai').should()
3    sinon = require('sinon')
4    proxyquire = require('proxyquire')
5    path = require('path')
6
7describe('directory', function () {
8
9    var directory,
10        _fs,
11        _mocks
12
13    beforeEach(function () {
14        _fs = {
15            'access': sinon.stub().callsArgWith(1, new Error()),
16            'mkdir': sinon.stub().callsArgWith(1, new Error())
17        }
18        _mocks = {
19            'fs': _fs,
20            'original-fs': _fs
21        }
22        directory = proxyquire('../lib/directory.js', _mocks)
23    })
24
25    it('does not create a directory when dir is root', function (done) {
26        directory.create('/', function (err) {
27            expect(_fs.mkdir.called).to.be.false
28            done();
29        })
30    })
31
32    if(require('os').platform() === 'win32') {
33        it('does not create a directory when dir is a windows root', function (done) {
34            directory.create('C:\\', function (err) {
35                expect(_fs.mkdir.called).to.be.false
36                done();
37            });
38        })
39
40        it('creates a windows directory without errors', function (done) {
41            _fs.mkdir.withArgs('C:\\a').callsArg(1);
42            directory.create('C:\\a', function (err) {
43                expect(err).to.not.be.ok
44                expect(_fs.mkdir.called).to.be.true
45                done();
46            });
47        })
48    }
49
50    it('creates a directory without errors', function (done) {
51        _fs.mkdir.withArgs('/a').callsArg(1);
52        directory.create('/a', function (err) {
53            expect(err).to.not.be.ok
54            expect(_fs.mkdir.called).to.be.true
55            done();
56        });
57    })
58
59    it('creates all directories in a path', function (done) {
60        _fs.mkdir.withArgs('/a').callsArg(1);
61        _fs.mkdir.withArgs('/a/b').callsArg(1);
62        _fs.mkdir.withArgs('/a/b/c').callsArg(1);
63        _fs.mkdir.withArgs('/a/b/c/d').callsArg(1);
64        directory.create('/a/b/c/d', function (err) {
65            expect(_fs.mkdir.calledWith('/a')).to.be.true
66            expect(_fs.mkdir.calledWith('/a/b')).to.be.true
67            expect(_fs.mkdir.calledWith('/a/b/c')).to.be.true
68            expect(_fs.mkdir.calledWith('/a/b/c/d')).to.be.true
69            done()
70        })
71    })
72
73    it('creates directory even if part of path already exists', function (done) {
74        _fs.mkdir.withArgs('/a').callsArgWith(1, {code: 'EEXIST'})
75        _fs.mkdir.withArgs('/a/b').callsArgWith(1, {code: 'EEXIST'})
76        _fs.mkdir.withArgs('/a/b/c').callsArg(1)
77        _fs.mkdir.withArgs('/a/b/c/d').callsArg(1)
78        directory.create('/a/b/c/d', function (err) {
79            expect(_fs.mkdir.calledWith('/a')).to.be.true
80            expect(_fs.mkdir.calledWith('/a/b')).to.be.true
81            expect(_fs.mkdir.calledWith('/a/b/c')).to.be.true
82            expect(_fs.mkdir.calledWith('/a/b/c/d')).to.be.true
83            done()
84        })
85    })
86
87    it('it succeeds even if path already exists', function (done) {
88        _fs.mkdir.callsArgWith(1, {code: 'EEXIST'})
89        directory.create('/a/b/c/d', function (err) {
90            expect(err).to.be.undefined
91            done()
92        })
93    })
94
95    it('creates a relative directory', function (done) {
96        _fs.mkdir.withArgs('a').callsArg(1);
97        directory.create('a', function (err) {
98            expect(_fs.mkdir.calledWith('a')).to.be.true
99            done()
100        })
101    })
102
103    it('creates all relative directories', function (done) {
104        _fs.mkdir.withArgs('a').callsArg(1);
105        _fs.mkdir.withArgs('a/b').callsArg(1);
106        _fs.mkdir.withArgs('a/b/c').callsArg(1);
107        directory.create('a/b/c', function (err) {
108            expect(_fs.mkdir.calledWith('a')).to.be.true
109            expect(_fs.mkdir.calledWith('a/b')).to.be.true
110            expect(_fs.mkdir.calledWith('a/b/c')).to.be.true
111            done()
112        })
113    })
114})
Full Screen

FileStream.js

Source: FileStream.js Github

copy
1const fs = require('fs');
2
3exports.createConfigFileInDashboard = (filePath, appName, mode = true,OtherProps) =>{
4    let props = '';
5    for (const [key, value] of Object.entries(OtherProps)) {
6        if(value != undefined)
7        props +=`${key}: ${value}, `;
8    }
9
10    // if(!fs.existsSync(filePath)){
11        let data = `app.constant('config', { APP_NAME :"${appName}", PRODUCTION: ${mode}, ${props} });`;
12        fs.writeFileSync(filePath, data)
13    // }
14};
15
16exports.dataOfStateCitiesFile = () => {
17    let data = fs.readFileSync(`${__dirname}/state_cities.json`);
18    return (JSON.parse(data))
19}
20
21exports.createEssentialDirectories = () => {
22    let uploads = './core/uploads';
23    let admin = `${uploads}/admin`;
24    let download = `${uploads}/download`;
25    let franchisee = `${uploads}/franchisee`;
26    let offers = `${uploads}/offers`;
27    let products = `${uploads}/products`;
28        let img = `${products}/img`;
29        let techDetails = `${products}/techDetails`;
30        let vis = `${products}/vis`;
31    let reps = `${uploads}/reps`;
32    let temp = `${uploads}/temp`;
33    let companyAbout = `${uploads}/companyAbout`;
34    let promotinalPics = `${uploads}/promotinalPics`;
35    let certificates = `${uploads}/certificates`;
36
37    if(!fs.existsSync(uploads)){
38        fs.mkdirSync(uploads);
39        fs.mkdirSync(admin);
40        fs.mkdirSync(download);
41        fs.mkdirSync(franchisee);
42        fs.mkdirSync(offers);
43        fs.mkdirSync(reps);
44        fs.mkdirSync(temp);
45        fs.mkdirSync(products);
46        fs.mkdirSync(img);
47        fs.mkdirSync(techDetails);
48        fs.mkdirSync(vis);
49        fs.mkdirSync(companyAbout);
50        fs.mkdirSync(promotinalPics);
51        fs.mkdirSync(certificates);
52    }
53    else{
54        if(!fs.existsSync(admin)) fs.mkdirSync(admin);
55        if(!fs.existsSync(download)) fs.mkdirSync(download);
56        if(!fs.existsSync(franchisee)) fs.mkdirSync(franchisee);
57        if(!fs.existsSync(offers)) fs.mkdirSync(offers);
58        if(!fs.existsSync(reps)) fs.mkdirSync(reps);
59        if(!fs.existsSync(temp)) fs.mkdirSync(temp);
60        if(!fs.existsSync(companyAbout)) fs.mkdirSync(companyAbout);
61        if(!fs.existsSync(promotinalPics)) fs.mkdirSync(promotinalPics);
62        if(!fs.existsSync(certificates)) fs.mkdirSync(certificates);
63
64        if(!fs.existsSync(products)) fs.mkdirSync(products);
65        else{
66            if(!fs.existsSync(img)) fs.mkdirSync(img);
67            if(!fs.existsSync(techDetails)) fs.mkdirSync(techDetails);
68            if(!fs.existsSync(vis)) fs.mkdirSync(vis);
69        }     
70    }
71}
72
Full Screen

test-fs-mkdir.js

Source: test-fs-mkdir.js Github

copy
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22'use strict';
23const common = require('../common');
24const assert = require('assert');
25const fs = require('fs');
26const path = require('path');
27
28const tmpdir = require('../common/tmpdir');
29tmpdir.refresh();
30
31let dirc = 0;
32function nextdir() {
33  return `test${++dirc}`;
34}
35
36// fs.mkdir creates directory using assigned path
37{
38  const pathname = path.join(tmpdir.path, nextdir());
39
40  fs.mkdir(pathname, common.mustCall(function(err) {
41    assert.strictEqual(err, null);
42    assert.strictEqual(fs.existsSync(pathname), true);
43  }));
44}
45
46// fs.mkdir creates directory with assigned mode value
47{
48  const pathname = path.join(tmpdir.path, nextdir());
49
50  fs.mkdir(pathname, 0o777, common.mustCall(function(err) {
51    assert.strictEqual(err, null);
52    assert.strictEqual(fs.existsSync(pathname), true);
53  }));
54}
55
56// fs.mkdir creates directory with mode passed as an options object
57{
58  const pathname = path.join(tmpdir.path, nextdir());
59
60  fs.mkdir(pathname, { mode: 0o777 }, common.mustCall(function(err) {
61    assert.strictEqual(err, null);
62    assert.strictEqual(fs.existsSync(pathname), true);
63  }));
64}
65
66// fs.mkdirSync creates directory with mode passed as an options object
67{
68  const pathname = path.join(tmpdir.path, nextdir());
69
70  fs.mkdirSync(pathname, { mode: 0o777 });
71
72  assert.strictEqual(fs.existsSync(pathname), true);
73}
74
75// mkdirSync successfully creates directory from given path
76{
77  const pathname = path.join(tmpdir.path, nextdir());
78
79  fs.mkdirSync(pathname);
80
81  const exists = fs.existsSync(pathname);
82  assert.strictEqual(exists, true);
83}
84
85// mkdirSync and mkdir require path to be a string, buffer or url.
86// Anything else generates an error.
87[false, 1, {}, [], null, undefined].forEach((i) => {
88  assert.throws(
89    () => fs.mkdir(i, common.mustNotCall()),
90    {
91      code: 'ERR_INVALID_ARG_TYPE',
92      name: 'TypeError'
93    }
94  );
95  assert.throws(
96    () => fs.mkdirSync(i),
97    {
98      code: 'ERR_INVALID_ARG_TYPE',
99      name: 'TypeError'
100    }
101  );
102});
103
104// mkdirpSync when both top-level, and sub-folders do not exist.
105{
106  const pathname = path.join(tmpdir.path, nextdir(), nextdir());
107
108  fs.mkdirSync(pathname, { recursive: true });
109
110  const exists = fs.existsSync(pathname);
111  assert.strictEqual(exists, true);
112  assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
113}
114
115// mkdirpSync when folder already exists.
116{
117  const pathname = path.join(tmpdir.path, nextdir(), nextdir());
118
119  fs.mkdirSync(pathname, { recursive: true });
120  // Should not cause an error.
121  fs.mkdirSync(pathname, { recursive: true });
122
123  const exists = fs.existsSync(pathname);
124  assert.strictEqual(exists, true);
125  assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
126}
127
128// mkdirpSync ../
129{
130  const pathname = `${tmpdir.path}/${nextdir()}/../${nextdir()}/${nextdir()}`;
131  fs.mkdirSync(pathname, { recursive: true });
132  const exists = fs.existsSync(pathname);
133  assert.strictEqual(exists, true);
134  assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
135}
136
137// mkdirpSync when path is a file.
138{
139  const pathname = path.join(tmpdir.path, nextdir(), nextdir());
140
141  fs.mkdirSync(path.dirname(pathname));
142  fs.writeFileSync(pathname, '', 'utf8');
143
144  assert.throws(
145    () => { fs.mkdirSync(pathname, { recursive: true }); },
146    {
147      code: 'EEXIST',
148      message: /EEXIST: .*mkdir/,
149      name: 'Error',
150      syscall: 'mkdir',
151    }
152  );
153}
154
155// mkdirpSync when part of the path is a file.
156{
157  const filename = path.join(tmpdir.path, nextdir(), nextdir());
158  const pathname = path.join(filename, nextdir(), nextdir());
159
160  fs.mkdirSync(path.dirname(filename));
161  fs.writeFileSync(filename, '', 'utf8');
162
163  assert.throws(
164    () => { fs.mkdirSync(pathname, { recursive: true }); },
165    {
166      code: 'ENOTDIR',
167      message: /ENOTDIR: .*mkdir/,
168      name: 'Error',
169      syscall: 'mkdir',
170      path: pathname // See: https://github.com/nodejs/node/issues/28015
171    }
172  );
173}
174
175// `mkdirp` when folder does not yet exist.
176{
177  const pathname = path.join(tmpdir.path, nextdir(), nextdir());
178
179  fs.mkdir(pathname, { recursive: true }, common.mustCall(function(err) {
180    assert.strictEqual(err, null);
181    assert.strictEqual(fs.existsSync(pathname), true);
182    assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
183  }));
184}
185
186// `mkdirp` when path is a file.
187{
188  const pathname = path.join(tmpdir.path, nextdir(), nextdir());
189
190  fs.mkdirSync(path.dirname(pathname));
191  fs.writeFileSync(pathname, '', 'utf8');
192  fs.mkdir(pathname, { recursive: true }, common.mustCall((err) => {
193    assert.strictEqual(err.code, 'EEXIST');
194    assert.strictEqual(err.syscall, 'mkdir');
195    assert.strictEqual(fs.statSync(pathname).isDirectory(), false);
196  }));
197}
198
199// `mkdirp` when part of the path is a file.
200{
201  const filename = path.join(tmpdir.path, nextdir(), nextdir());
202  const pathname = path.join(filename, nextdir(), nextdir());
203
204  fs.mkdirSync(path.dirname(filename));
205  fs.writeFileSync(filename, '', 'utf8');
206  fs.mkdir(pathname, { recursive: true }, common.mustCall((err) => {
207    assert.strictEqual(err.code, 'ENOTDIR');
208    assert.strictEqual(err.syscall, 'mkdir');
209    assert.strictEqual(fs.existsSync(pathname), false);
210    // See: https://github.com/nodejs/node/issues/28015
211    // The path field varies slightly in Windows errors, vs., other platforms
212    // see: https://github.com/libuv/libuv/issues/2661, for this reason we
213    // use startsWith() rather than comparing to the full "pathname".
214    assert(err.path.startsWith(filename));
215  }));
216}
217
218// mkdirpSync dirname loop
219// XXX: windows and smartos have issues removing a directory that you're in.
220if (common.isMainThread && (common.isLinux || common.isOSX)) {
221  const pathname = path.join(tmpdir.path, nextdir());
222  fs.mkdirSync(pathname);
223  process.chdir(pathname);
224  fs.rmdirSync(pathname);
225  assert.throws(
226    () => { fs.mkdirSync('X', { recursive: true }); },
227    {
228      code: 'ENOENT',
229      message: /ENOENT: .*mkdir/,
230      name: 'Error',
231      syscall: 'mkdir',
232    }
233  );
234  fs.mkdir('X', { recursive: true }, (err) => {
235    assert.strictEqual(err.code, 'ENOENT');
236    assert.strictEqual(err.syscall, 'mkdir');
237  });
238}
239
240// mkdirSync and mkdir require options.recursive to be a boolean.
241// Anything else generates an error.
242{
243  const pathname = path.join(tmpdir.path, nextdir());
244  ['', 1, {}, [], null, Symbol('test'), () => {}].forEach((recursive) => {
245    const received = common.invalidArgTypeHelper(recursive);
246    assert.throws(
247      () => fs.mkdir(pathname, { recursive }, common.mustNotCall()),
248      {
249        code: 'ERR_INVALID_ARG_TYPE',
250        name: 'TypeError',
251        message: 'The "options.recursive" property must be of type boolean.' +
252          received
253      }
254    );
255    assert.throws(
256      () => fs.mkdirSync(pathname, { recursive }),
257      {
258        code: 'ERR_INVALID_ARG_TYPE',
259        name: 'TypeError',
260        message: 'The "options.recursive" property must be of type boolean.' +
261          received
262      }
263    );
264  });
265}
266
267// `mkdirp` returns first folder created, when all folders are new.
268{
269  const dir1 = nextdir();
270  const dir2 = nextdir();
271  const firstPathCreated = path.join(tmpdir.path, dir1);
272  const pathname = path.join(tmpdir.path, dir1, dir2);
273
274  fs.mkdir(pathname, { recursive: true }, common.mustCall(function(err, path) {
275    assert.strictEqual(err, null);
276    assert.strictEqual(fs.existsSync(pathname), true);
277    assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
278    assert.strictEqual(path, firstPathCreated);
279  }));
280}
281
282// `mkdirp` returns first folder created, when last folder is new.
283{
284  const dir1 = nextdir();
285  const dir2 = nextdir();
286  const pathname = path.join(tmpdir.path, dir1, dir2);
287  fs.mkdirSync(path.join(tmpdir.path, dir1));
288  fs.mkdir(pathname, { recursive: true }, common.mustCall(function(err, path) {
289    assert.strictEqual(err, null);
290    assert.strictEqual(fs.existsSync(pathname), true);
291    assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
292    assert.strictEqual(path, pathname);
293  }));
294}
295
296// `mkdirp` returns undefined, when no new folders are created.
297{
298  const dir1 = nextdir();
299  const dir2 = nextdir();
300  const pathname = path.join(tmpdir.path, dir1, dir2);
301  fs.mkdirSync(path.join(tmpdir.path, dir1, dir2), { recursive: true });
302  fs.mkdir(pathname, { recursive: true }, common.mustCall(function(err, path) {
303    assert.strictEqual(err, null);
304    assert.strictEqual(fs.existsSync(pathname), true);
305    assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
306    assert.strictEqual(path, undefined);
307  }));
308}
309
310// `mkdirp.sync` returns first folder created, when all folders are new.
311{
312  const dir1 = nextdir();
313  const dir2 = nextdir();
314  const firstPathCreated = path.join(tmpdir.path, dir1);
315  const pathname = path.join(tmpdir.path, dir1, dir2);
316  const p = fs.mkdirSync(pathname, { recursive: true });
317  assert.strictEqual(fs.existsSync(pathname), true);
318  assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
319  assert.strictEqual(p, firstPathCreated);
320}
321
322// `mkdirp.sync` returns first folder created, when last folder is new.
323{
324  const dir1 = nextdir();
325  const dir2 = nextdir();
326  const pathname = path.join(tmpdir.path, dir1, dir2);
327  fs.mkdirSync(path.join(tmpdir.path, dir1), { recursive: true });
328  const p = fs.mkdirSync(pathname, { recursive: true });
329  assert.strictEqual(fs.existsSync(pathname), true);
330  assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
331  assert.strictEqual(p, pathname);
332}
333
334// `mkdirp.sync` returns undefined, when no new folders are created.
335{
336  const dir1 = nextdir();
337  const dir2 = nextdir();
338  const pathname = path.join(tmpdir.path, dir1, dir2);
339  fs.mkdirSync(path.join(tmpdir.path, dir1, dir2), { recursive: true });
340  const p = fs.mkdirSync(pathname, { recursive: true });
341  assert.strictEqual(fs.existsSync(pathname), true);
342  assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
343  assert.strictEqual(p, undefined);
344}
345
346// `mkdirp.promises` returns first folder created, when all folders are new.
347{
348  const dir1 = nextdir();
349  const dir2 = nextdir();
350  const firstPathCreated = path.join(tmpdir.path, dir1);
351  const pathname = path.join(tmpdir.path, dir1, dir2);
352  async function testCase() {
353    const p = await fs.promises.mkdir(pathname, { recursive: true });
354    assert.strictEqual(fs.existsSync(pathname), true);
355    assert.strictEqual(fs.statSync(pathname).isDirectory(), true);
356    assert.strictEqual(p, firstPathCreated);
357  }
358  testCase();
359}
360
361// Keep the event loop alive so the async mkdir() requests
362// have a chance to run (since they don't ref the event loop).
363process.nextTick(() => {});
364
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Cypress on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)