forked from MetaMask/utils
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfs.test.ts
748 lines (626 loc) · 23.9 KB
/
fs.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
import fs from 'fs';
import { when } from 'jest-when';
import os from 'os';
import path from 'path';
import util from 'util';
import {
createSandbox,
directoryExists,
ensureDirectoryStructureExists,
fileExists,
forceRemove,
readFile,
readJsonFile,
writeFile,
writeJsonFile,
} from './fs';
const { withinSandbox } = createSandbox('utils');
describe('fs', () => {
describe('readFile', () => {
it('reads the contents of the given file as a UTF-8-encoded string', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.file');
await fs.promises.writeFile(filePath, 'some content 😄');
expect(await readFile(filePath)).toBe('some content 😄');
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'nonexistent.file');
await expect(readFile(filePath)).rejects.toThrow(
expect.objectContaining({
message: `Could not read file '${filePath}'`,
code: 'ENOENT',
stack: expect.any(String),
cause: expect.objectContaining({
message: `ENOENT: no such file or directory, open '${filePath}'`,
code: 'ENOENT',
}),
}),
);
});
});
});
describe('writeFile', () => {
it('writes the given data to the given file', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.file');
await writeFile(filePath, 'some content 😄');
expect(await fs.promises.readFile(filePath, 'utf8')).toBe(
'some content 😄',
);
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
// Make sandbox root directory non-readable
await fs.promises.chmod(sandbox.directoryPath, 0o600);
const filePath = path.join(sandbox.directoryPath, 'test.file');
await expect(writeFile(filePath, 'some content 😄')).rejects.toThrow(
expect.objectContaining({
message: `Could not write file '${filePath}'`,
code: 'EACCES',
stack: expect.any(String),
cause: expect.objectContaining({
code: 'EACCES',
}),
}),
);
});
});
});
describe('readJsonFile', () => {
describe('not given a custom parser', () => {
it('reads the contents of the given file as a UTF-8-encoded string and parses it using the JSON module', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
await fs.promises.writeFile(filePath, '{"foo": "bar 😄"}');
expect(await readJsonFile(filePath)).toStrictEqual({ foo: 'bar 😄' });
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'nonexistent.json');
await expect(readJsonFile(filePath)).rejects.toThrow(
expect.objectContaining({
message: `Could not read JSON file '${filePath}'`,
code: 'ENOENT',
stack: expect.any(String),
cause: expect.objectContaining({
message: `ENOENT: no such file or directory, open '${filePath}'`,
code: 'ENOENT',
}),
}),
);
});
});
});
describe('given a custom parser', () => {
it('reads the contents of the given file as a UTF-8-encoded string and parses it using the custom parser', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
const parser = {
parse(content: string) {
return { content };
},
};
await fs.promises.writeFile(filePath, '{"foo": "bar 😄"}');
expect(await readJsonFile(filePath, { parser })).toStrictEqual({
content: '{"foo": "bar 😄"}',
});
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'nonexistent.json');
const parser = {
parse(content: string) {
return { content };
},
};
await expect(readJsonFile(filePath, { parser })).rejects.toThrow(
expect.objectContaining({
message: `Could not read JSON file '${filePath}'`,
code: 'ENOENT',
stack: expect.any(String),
cause: expect.objectContaining({
message: `ENOENT: no such file or directory, open '${filePath}'`,
code: 'ENOENT',
}),
}),
);
});
});
});
});
describe('writeJsonFile', () => {
describe('not given a custom stringifier', () => {
it('writes the given data to the given file as JSON (not reformatting it by default)', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
await writeJsonFile(filePath, { foo: 'bar 😄' });
expect(await fs.promises.readFile(filePath, 'utf8')).toBe(
'{"foo":"bar 😄"}',
);
});
});
it('writes the given data to the given file as JSON (not reformatting it if "prettify" is false)', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
await writeJsonFile(filePath, { foo: 'bar 😄' }, { prettify: false });
expect(await fs.promises.readFile(filePath, 'utf8')).toBe(
'{"foo":"bar 😄"}',
);
});
});
it('writes the given data to the given file as JSON (reformatting it if "prettify" is true)', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
await writeJsonFile(filePath, { foo: 'bar 😄' }, { prettify: true });
expect(await fs.promises.readFile(filePath, 'utf8')).toBe(
'{\n "foo": "bar 😄"\n}',
);
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
// Make sandbox root directory non-readable
await fs.promises.chmod(sandbox.directoryPath, 0o600);
const filePath = path.join(sandbox.directoryPath, 'test.json');
await expect(
writeJsonFile(filePath, { foo: 'bar 😄' }),
).rejects.toThrow(
expect.objectContaining({
message: `Could not write JSON file '${filePath}'`,
code: 'EACCES',
stack: expect.any(String),
cause: expect.objectContaining({
code: 'EACCES',
}),
}),
);
});
});
});
describe('given a custom stringifier', () => {
it('writes the given data to the given file as JSON, using the stringifier (not reformatting it by default)', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
const stringifier = {
stringify(
json: any,
replacer?:
| ((this: any, key: string, value: any) => any)
| (number | string)[]
| null,
space?: string,
) {
return (
`${util.inspect(json)}\n` +
`replacer: ${util.inspect(replacer)}, space: ${util.inspect(
space,
)}`
);
},
};
await writeJsonFile(filePath, { foo: 'bar 😄' }, { stringifier });
expect(await fs.promises.readFile(filePath, 'utf8')).toBe(
`{ foo: 'bar 😄' }\nreplacer: undefined, space: undefined`,
);
});
});
it('writes the given data to the given file as JSON (not reformatting it if "prettify" is false)', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
const stringifier = {
stringify(
json: any,
replacer?:
| ((this: any, key: string, value: any) => any)
| (number | string)[]
| null,
space?: string,
) {
return (
`${util.inspect(json)}\n` +
`replacer: ${util.inspect(replacer)}, space: ${util.inspect(
space,
)}`
);
},
};
await writeJsonFile(
filePath,
{ foo: 'bar 😄' },
{ stringifier, prettify: false },
);
expect(await fs.promises.readFile(filePath, 'utf8')).toBe(
`{ foo: 'bar 😄' }\nreplacer: undefined, space: undefined`,
);
});
});
it('writes the given data to the given file as JSON (reformatting it if "prettify" is true)', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.json');
const stringifier = {
stringify(
json: any,
replacer?:
| ((this: any, key: string, value: any) => any)
| (number | string)[]
| null,
space?: string,
) {
return (
`${util.inspect(json)}\n` +
`replacer: ${util.inspect(replacer)}, space: ${util.inspect(
space,
)}`
);
},
};
await writeJsonFile(
filePath,
{ foo: 'bar 😄' },
{ stringifier, prettify: true },
);
expect(await fs.promises.readFile(filePath, 'utf8')).toBe(
`{ foo: 'bar 😄' }\nreplacer: null, space: ' '`,
);
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
// Make sandbox root directory non-readable
await fs.promises.chmod(sandbox.directoryPath, 0o600);
const filePath = path.join(sandbox.directoryPath, 'test.json');
const stringifier = {
stringify(
json: any,
replacer?:
| ((this: any, key: string, value: any) => any)
| (number | string)[]
| null,
space?: string,
) {
return (
`${util.inspect(json)}\n` +
`replacer: ${util.inspect(replacer)}, space: ${util.inspect(
space,
)}`
);
},
};
await expect(
writeJsonFile(filePath, { foo: 'bar 😄' }, { stringifier }),
).rejects.toThrow(
expect.objectContaining({
message: `Could not write JSON file '${filePath}'`,
code: 'EACCES',
stack: expect.any(String),
cause: expect.objectContaining({
code: 'EACCES',
}),
}),
);
});
});
});
});
describe('fileExists', () => {
it('returns true if the given path refers to an existing file', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.file');
await fs.promises.writeFile(filePath, 'some content');
expect(await fileExists(filePath)).toBe(true);
});
});
it('returns false if the given path refers to something that is not a file', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const directoryPath = path.join(
sandbox.directoryPath,
'test-directory',
);
await fs.promises.mkdir(directoryPath);
expect(await fileExists(directoryPath)).toBe(false);
});
});
it('returns false if the given path does not refer to any existing entry', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'nonexistent-entry');
expect(await fileExists(filePath)).toBe(false);
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
const entryPath = '/some/file';
const error: any = new Error('oops');
error.code = 'ESOMETHING';
error.stack = 'some stack';
when(jest.spyOn(fs.promises, 'stat'))
.calledWith(entryPath)
.mockRejectedValue(error);
await expect(fileExists(entryPath)).rejects.toThrow(
expect.objectContaining({
message: `Could not determine if file exists '${entryPath}'`,
code: 'ESOMETHING',
stack: expect.any(String),
cause: error,
}),
);
});
});
describe('directoryExists', () => {
it('returns true if the given path refers to an existing directory', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const directoryPath = path.join(
sandbox.directoryPath,
'test-directory',
);
await fs.promises.mkdir(directoryPath);
expect(await directoryExists(directoryPath)).toBe(true);
});
});
it('returns false if the given path refers to something that is not a directory', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.file');
await fs.promises.writeFile(filePath, 'some content');
expect(await directoryExists(filePath)).toBe(false);
});
});
it('returns false if the given path does not refer to any existing entry', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const directoryPath = path.join(
sandbox.directoryPath,
'nonexistent-entry',
);
expect(await directoryExists(directoryPath)).toBe(false);
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
const entryPath = '/some/file';
const error: any = new Error('oops');
error.code = 'ESOMETHING';
error.stack = 'some stack';
when(jest.spyOn(fs.promises, 'stat'))
.calledWith(entryPath)
.mockRejectedValue(error);
await expect(directoryExists(entryPath)).rejects.toThrow(
expect.objectContaining({
message: `Could not determine if directory exists '${entryPath}'`,
cause: error,
stack: expect.any(String),
}),
);
});
});
describe('ensureDirectoryStructureExists', () => {
it('creates directories leading up to and including the given path', async () => {
expect.assertions(3);
await withinSandbox(async (sandbox) => {
const directoryPath = path.join(sandbox.directoryPath, 'a', 'b', 'c');
await ensureDirectoryStructureExists(directoryPath);
// None of the `await`s below should throw.
expect(
await fs.promises.readdir(path.join(sandbox.directoryPath, 'a')),
).toStrictEqual(expect.anything());
expect(
await fs.promises.readdir(path.join(sandbox.directoryPath, 'a', 'b')),
).toStrictEqual(expect.anything());
expect(
await fs.promises.readdir(
path.join(sandbox.directoryPath, 'a', 'b', 'c'),
),
).toStrictEqual(expect.anything());
});
});
it('does not throw an error, returning undefined, if the given directory already exists', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const directoryPath = path.join(sandbox.directoryPath, 'a', 'b', 'c');
await fs.promises.mkdir(path.join(sandbox.directoryPath, 'a'));
await fs.promises.mkdir(path.join(sandbox.directoryPath, 'a', 'b'));
await fs.promises.mkdir(
path.join(sandbox.directoryPath, 'a', 'b', 'c'),
);
expect(
await ensureDirectoryStructureExists(directoryPath),
).toBeUndefined();
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
// Make sandbox root directory non-readable
await fs.promises.chmod(sandbox.directoryPath, 0o600);
const directoryPath = path.join(
sandbox.directoryPath,
'test-directory',
);
await expect(
ensureDirectoryStructureExists(directoryPath),
).rejects.toThrow(
expect.objectContaining({
message: `Could not create directory structure '${directoryPath}'`,
code: 'EACCES',
stack: expect.any(String),
cause: expect.objectContaining({
code: 'EACCES',
}),
}),
);
});
});
});
describe('forceRemove', () => {
describe('given a file path', () => {
it('removes the file', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.file');
await fs.promises.writeFile(filePath, 'some content');
expect(await forceRemove(filePath)).toBeUndefined();
});
});
it('does nothing if the path does not exist', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const filePath = path.join(sandbox.directoryPath, 'test.file');
expect(await forceRemove(filePath)).toBeUndefined();
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
const filePath = '/some/file';
const error: any = new Error('oops');
error.code = 'ESOMETHING';
error.stack = 'some stack';
when(jest.spyOn(fs.promises, 'rm'))
.calledWith(filePath, {
recursive: true,
force: true,
})
.mockRejectedValue(error);
await expect(forceRemove(filePath)).rejects.toThrow(
expect.objectContaining({
message: `Could not remove file or directory '${filePath}'`,
code: 'ESOMETHING',
stack: expect.any(String),
cause: error,
}),
);
});
});
describe('given a directory path', () => {
it('removes the directory', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const directoryPath = path.join(
sandbox.directoryPath,
'test-directory',
);
await fs.promises.mkdir(directoryPath);
expect(await forceRemove(directoryPath)).toBeUndefined();
});
});
it('does nothing if the path does not exist', async () => {
expect.assertions(1);
await withinSandbox(async (sandbox) => {
const directoryPath = path.join(
sandbox.directoryPath,
'test-directory',
);
expect(await forceRemove(directoryPath)).toBeUndefined();
});
});
it('re-throws a wrapped version of any error that occurs, assigning it the same code and giving it a stack', async () => {
const directoryPath = '/some/directory';
const error: any = new Error('oops');
error.code = 'ESOMETHING';
error.stack = 'some stack';
when(jest.spyOn(fs.promises, 'rm'))
.calledWith(directoryPath, {
recursive: true,
force: true,
})
.mockRejectedValue(error);
await expect(forceRemove(directoryPath)).rejects.toThrow(
expect.objectContaining({
message: `Could not remove file or directory '${directoryPath}'`,
code: 'ESOMETHING',
cause: error,
stack: expect.any(String),
}),
);
});
});
});
describe('createSandbox', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('does not create the sandbox directory immediately', async () => {
createSandbox('utils-fs');
const sandboxDirectoryPath = path.join(os.tmpdir(), 'utils-fs');
await expect(fs.promises.stat(sandboxDirectoryPath)).rejects.toThrow(
'ENOENT',
);
});
describe('withinSandbox', () => {
it('creates the sandbox directory and keeps it around before its given function ends', async () => {
expect.assertions(1);
const nowTimestamp = new Date('2023-01-01').getTime();
jest.setSystemTime(nowTimestamp);
const { withinSandbox: withinTestSandbox } = createSandbox('utils-fs');
const sandboxDirectoryPath = path.join(
os.tmpdir(),
`utils-fs--${nowTimestamp}`,
);
await withinTestSandbox(async () => {
expect(await fs.promises.stat(sandboxDirectoryPath)).toStrictEqual(
expect.anything(),
);
});
});
it('removes the sandbox directory after its given function ends', async () => {
const nowTimestamp = new Date('2023-01-01').getTime();
jest.setSystemTime(nowTimestamp);
const { withinSandbox: withinTestSandbox } = createSandbox('utils-fs');
const sandboxDirectoryPath = path.join(
os.tmpdir(),
`utils-fs--${nowTimestamp}`,
);
await withinTestSandbox(async () => {
// do nothing
});
await expect(fs.promises.stat(sandboxDirectoryPath)).rejects.toThrow(
'ENOENT',
);
});
it('throws if the sandbox directory already exists', async () => {
const nowTimestamp = new Date('2023-01-01').getTime();
jest.setSystemTime(nowTimestamp);
const { withinSandbox: withinTestSandbox } = createSandbox('utils-fs');
const sandboxDirectoryPath = path.join(
os.tmpdir(),
`utils-fs--${nowTimestamp}`,
);
try {
await fs.promises.mkdir(sandboxDirectoryPath);
await expect(
withinTestSandbox(async (_sandbox) => {
// do nothing
}),
).rejects.toThrow(
`${sandboxDirectoryPath} already exists. Cannot continue.`,
);
} finally {
await fs.promises.rm(sandboxDirectoryPath, { recursive: true });
}
});
});
});
});