summaryrefslogtreecommitdiff
path: root/test/parallel/test-fs-promises.js
blob: 3c7903c98f04d2c97e4c187ff0307f5b622b88ab (plain)
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
'use strict';

const common = require('../common');
const assert = require('assert');
const tmpdir = require('../common/tmpdir');
const fixtures = require('../common/fixtures');
const path = require('path');
const fs = require('fs');
const fsPromises = fs.promises;
const {
  access,
  chmod,
  chown,
  copyFile,
  lchown,
  link,
  lchmod,
  lstat,
  mkdir,
  mkdtemp,
  open,
  readFile,
  readdir,
  readlink,
  realpath,
  rename,
  rmdir,
  stat,
  symlink,
  truncate,
  unlink,
  utimes,
  writeFile
} = fsPromises;

const tmpDir = tmpdir.path;

let dirc = 0;
function nextdir() {
  return `test${++dirc}`;
}

// fs.promises should be enumerable.
assert.strictEqual(
  Object.prototype.propertyIsEnumerable.call(fs, 'promises'),
  true
);

{
  access(__filename, 'r')
    .then(common.mustCall());

  access('this file does not exist', 'r')
    .then(common.mustNotCall())
    .catch(common.expectsError({
      code: 'ENOENT',
      type: Error,
      message:
        /^ENOENT: no such file or directory, access/
    }));
}

function verifyStatObject(stat) {
  assert.strictEqual(typeof stat, 'object');
  assert.strictEqual(typeof stat.dev, 'number');
  assert.strictEqual(typeof stat.mode, 'number');
}

async function getHandle(dest) {
  await copyFile(fixtures.path('baz.js'), dest);
  await access(dest, 'r');

  return open(dest, 'r+');
}

{
  async function doTest() {
    tmpdir.refresh();

    const dest = path.resolve(tmpDir, 'baz.js');

    // handle is object
    {
      const handle = await getHandle(dest);
      assert.strictEqual(typeof handle, 'object');
      await handle.close();
    }

    // file stats
    {
      const handle = await getHandle(dest);
      let stats = await handle.stat();
      verifyStatObject(stats);
      assert.strictEqual(stats.size, 35);

      await handle.truncate(1);

      stats = await handle.stat();
      verifyStatObject(stats);
      assert.strictEqual(stats.size, 1);

      stats = await stat(dest);
      verifyStatObject(stats);

      stats = await handle.stat();
      verifyStatObject(stats);

      await handle.datasync();
      await handle.sync();
      await handle.close();
    }

    // Test fs.read promises when length to read is zero bytes
    {
      const dest = path.resolve(tmpDir, 'test1.js');
      const handle = await getHandle(dest);
      const buf = Buffer.from('DAWGS WIN');
      const bufLen = buf.length;
      await handle.write(buf);
      const ret = await handle.read(Buffer.alloc(bufLen), 0, 0, 0);
      assert.strictEqual(ret.bytesRead, 0);

      await unlink(dest);
      await handle.close();
    }

    // Bytes written to file match buffer
    {
      const handle = await getHandle(dest);
      const buf = Buffer.from('hello fsPromises');
      const bufLen = buf.length;
      await handle.write(buf);
      const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0);
      assert.strictEqual(ret.bytesRead, bufLen);
      assert.deepStrictEqual(ret.buffer, buf);
      await handle.close();
    }

    // Truncate file to specified length
    {
      const handle = await getHandle(dest);
      const buf = Buffer.from('hello FileHandle');
      const bufLen = buf.length;
      await handle.write(buf, 0, bufLen, 0);
      const ret = await handle.read(Buffer.alloc(bufLen), 0, bufLen, 0);
      assert.strictEqual(ret.bytesRead, bufLen);
      assert.deepStrictEqual(ret.buffer, buf);
      await truncate(dest, 5);
      assert.deepStrictEqual((await readFile(dest)).toString(), 'hello');
      await handle.close();
    }

    // Invalid change of ownership
    {
      const handle = await getHandle(dest);

      await chmod(dest, 0o666);
      await handle.chmod(0o666);

      await chmod(dest, (0o10777));
      await handle.chmod(0o10777);

      if (!common.isWindows) {
        await chown(dest, process.getuid(), process.getgid());
        await handle.chown(process.getuid(), process.getgid());
      }

      assert.rejects(
        async () => {
          await chown(dest, 1, -1);
        },
        {
          code: 'ERR_OUT_OF_RANGE',
          name: 'RangeError',
          message: 'The value of "gid" is out of range. ' +
                  'It must be >= 0 && < 4294967296. Received -1'
        });

      assert.rejects(
        async () => {
          await handle.chown(1, -1);
        },
        {
          code: 'ERR_OUT_OF_RANGE',
          name: 'RangeError',
          message: 'The value of "gid" is out of range. ' +
                    'It must be >= 0 && < 4294967296. Received -1'
        });

      await handle.close();
    }

    // Set modification times
    {
      const handle = await getHandle(dest);

      await utimes(dest, new Date(), new Date());

      try {
        await handle.utimes(new Date(), new Date());
      } catch (err) {
        // Some systems do not have futimes. If there is an error,
        // expect it to be ENOSYS
        common.expectsError({
          code: 'ENOSYS',
          type: Error
        })(err);
      }

      await handle.close();
    }

    // create symlink
    {
      const newPath = path.resolve(tmpDir, 'baz2.js');
      await rename(dest, newPath);
      let stats = await stat(newPath);
      verifyStatObject(stats);

      if (common.canCreateSymLink()) {
        const newLink = path.resolve(tmpDir, 'baz3.js');
        await symlink(newPath, newLink);
        if (!common.isWindows) {
          await lchown(newLink, process.getuid(), process.getgid());
        }
        stats = await lstat(newLink);
        verifyStatObject(stats);

        assert.strictEqual(newPath.toLowerCase(),
                           (await realpath(newLink)).toLowerCase());
        assert.strictEqual(newPath.toLowerCase(),
                           (await readlink(newLink)).toLowerCase());

        const newMode = 0o666;
        if (common.isOSX) {
          // `lchmod` is only available on macOS.
          await lchmod(newLink, newMode);
          stats = await lstat(newLink);
          assert.strictEqual(stats.mode & 0o777, newMode);
        } else {
          await Promise.all([
            assert.rejects(
              lchmod(newLink, newMode),
              common.expectsError({
                code: 'ERR_METHOD_NOT_IMPLEMENTED',
                type: Error,
                message: 'The lchmod() method is not implemented'
              })
            )
          ]);
        }

        await unlink(newLink);
      }
    }

    // create hard link
    {
      const newPath = path.resolve(tmpDir, 'baz2.js');
      const newLink = path.resolve(tmpDir, 'baz4.js');
      await link(newPath, newLink);

      await unlink(newLink);
    }

    // Testing readdir lists both files and directories
    {
      const newDir = path.resolve(tmpDir, 'dir');
      const newFile = path.resolve(tmpDir, 'foo.js');

      await mkdir(newDir);
      await writeFile(newFile, 'DAWGS WIN!', 'utf8');

      const stats = await stat(newDir);
      assert(stats.isDirectory());
      const list = await readdir(tmpDir);
      assert.notStrictEqual(list.indexOf('dir'), -1);
      assert.notStrictEqual(list.indexOf('foo.js'), -1);
      await rmdir(newDir);
      await unlink(newFile);
    }

    // `mkdir` when options is number.
    {
      const dir = path.join(tmpDir, nextdir());
      await mkdir(dir, 777);
      const stats = await stat(dir);
      assert(stats.isDirectory());
    }

    // `mkdir` when options is string.
    {
      const dir = path.join(tmpDir, nextdir());
      await mkdir(dir, '777');
      const stats = await stat(dir);
      assert(stats.isDirectory());
    }

    // `mkdirp` when folder does not yet exist.
    {
      const dir = path.join(tmpDir, nextdir(), nextdir());
      await mkdir(dir, { recursive: true });
      const stats = await stat(dir);
      assert(stats.isDirectory());
    }

    // `mkdirp` when path is a file.
    {
      const dir = path.join(tmpDir, nextdir(), nextdir());
      await mkdir(path.dirname(dir));
      await writeFile(dir);
      assert.rejects(
        mkdir(dir, { recursive: true }),
        {
          code: 'EEXIST',
          message: /EEXIST: .*mkdir/,
          name: 'Error',
          syscall: 'mkdir',
        }
      );
    }

    // `mkdirp` when part of the path is a file.
    {
      const file = path.join(tmpDir, nextdir(), nextdir());
      const dir = path.join(file, nextdir(), nextdir());
      await mkdir(path.dirname(file));
      await writeFile(file);
      assert.rejects(
        mkdir(dir, { recursive: true }),
        {
          code: 'ENOTDIR',
          message: /ENOTDIR: .*mkdir/,
          name: 'Error',
          syscall: 'mkdir',
        }
      );
    }

    // mkdirp ./
    {
      const dir = path.resolve(tmpDir, `${nextdir()}/./${nextdir()}`);
      await mkdir(dir, { recursive: true });
      const stats = await stat(dir);
      assert(stats.isDirectory());
    }

    // mkdirp ../
    {
      const dir = path.resolve(tmpDir, `${nextdir()}/../${nextdir()}`);
      await mkdir(dir, { recursive: true });
      const stats = await stat(dir);
      assert(stats.isDirectory());
    }

    // fs.mkdirp requires the recursive option to be of type boolean.
    // Everything else generates an error.
    {
      const dir = path.join(tmpDir, nextdir(), nextdir());
      ['', 1, {}, [], null, Symbol('test'), () => {}].forEach((recursive) => {
        assert.rejects(
          // mkdir() expects to get a boolean value for options.recursive.
          async () => mkdir(dir, { recursive }),
          {
            code: 'ERR_INVALID_ARG_TYPE',
            name: 'TypeError',
            message: 'The "recursive" argument must be of type boolean. ' +
              `Received type ${typeof recursive}`
          }
        );
      });
    }

    // `mkdtemp` with invalid numeric prefix
    {
      await mkdtemp(path.resolve(tmpDir, 'FOO'));
      assert.rejects(
        // mkdtemp() expects to get a string prefix.
        async () => mkdtemp(1),
        {
          code: 'ERR_INVALID_ARG_TYPE',
          name: 'TypeError'
        }
      );
    }

  }

  doTest().then(common.mustCall());
}