|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | + |
| 4 | +// tests if `filename` is provided to watcher on supported platforms |
| 5 | + |
| 6 | +const fs = require('fs'); |
| 7 | +const assert = require('assert'); |
| 8 | +const { join } = require('path'); |
| 9 | + |
| 10 | +class WatchTestCase { |
| 11 | + constructor(shouldInclude, dirName, fileName, field) { |
| 12 | + this.dirName = dirName; |
| 13 | + this.fileName = fileName; |
| 14 | + this.field = field; |
| 15 | + this.shouldSkip = !shouldInclude; |
| 16 | + } |
| 17 | + get dirPath() { return join(common.tmpDir, this.dirName); } |
| 18 | + get filePath() { return join(this.dirPath, this.fileName); } |
| 19 | +} |
| 20 | + |
| 21 | +const cases = [ |
| 22 | + // Watch on a directory should callback with a filename on supported systems |
| 23 | + new WatchTestCase( |
| 24 | + common.isLinux || common.isOSX || common.isWindows || common.isAix, |
| 25 | + 'watch1', |
| 26 | + 'foo', |
| 27 | + 'filePath' |
| 28 | + ), |
| 29 | + // Watch on a file should callback with a filename on supported systems |
| 30 | + new WatchTestCase( |
| 31 | + common.isLinux || common.isOSX || common.isWindows, |
| 32 | + 'watch2', |
| 33 | + 'bar', |
| 34 | + 'dirPath' |
| 35 | + ) |
| 36 | +]; |
| 37 | + |
| 38 | +common.refreshTmpDir(); |
| 39 | + |
| 40 | +for (const testCase of cases) { |
| 41 | + if (testCase.shouldSkip) continue; |
| 42 | + fs.mkdirSync(testCase.dirPath); |
| 43 | + // long content so it's actually flushed. |
| 44 | + const content1 = Date.now() + testCase.fileName.toLowerCase().repeat(1e4); |
| 45 | + fs.writeFileSync(testCase.filePath, content1); |
| 46 | + |
| 47 | + let interval; |
| 48 | + const watcher = fs.watch(testCase[testCase.field]); |
| 49 | + watcher.on('error', (err) => { |
| 50 | + if (interval) { |
| 51 | + clearInterval(interval); |
| 52 | + interval = null; |
| 53 | + } |
| 54 | + assert.fail(err); |
| 55 | + }); |
| 56 | + watcher.on('change', common.mustCall(function(eventType, argFilename) { |
| 57 | + if (interval) { |
| 58 | + clearInterval(interval); |
| 59 | + interval = null; |
| 60 | + } |
| 61 | + if (common.isOSX) |
| 62 | + assert.strictEqual(['rename', 'change'].includes(eventType), true); |
| 63 | + else |
| 64 | + assert.strictEqual(eventType, 'change'); |
| 65 | + assert.strictEqual(argFilename, testCase.fileName); |
| 66 | + |
| 67 | + // end of test case |
| 68 | + watcher.close(); |
| 69 | + })); |
| 70 | + |
| 71 | + // long content so it's actually flushed. toUpperCase so there's real change. |
| 72 | + const content2 = Date.now() + testCase.fileName.toUpperCase().repeat(1e4); |
| 73 | + interval = setInterval(() => { |
| 74 | + fs.writeFileSync(testCase.filePath, ''); |
| 75 | + fs.writeFileSync(testCase.filePath, content2); |
| 76 | + }, 100); |
| 77 | +} |
0 commit comments