|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const path = require('path'); |
| 5 | +const readShebang = require('./readShebang'); |
| 6 | + |
| 7 | +describe('readShebang', () => { |
| 8 | + afterEach(() => jest.restoreAllMocks()); |
| 9 | + |
| 10 | + it('should read the shebang command', () => { |
| 11 | + const close = jest.spyOn(fs, 'closeSync'); |
| 12 | + |
| 13 | + expect(readShebang(path.join(__dirname, '../../test/fixtures/shebang'))).toBe('node'); |
| 14 | + expect(close).toHaveBeenCalledTimes(1); |
| 15 | + }); |
| 16 | + |
| 17 | + it('should return null if the file has no shebang', () => { |
| 18 | + expect(readShebang(path.join(__dirname, '../../test/fixtures/echo.js'))).toBe(null); |
| 19 | + }); |
| 20 | + |
| 21 | + it('should close the file descriptor when reading fails, including descriptor zero', () => { |
| 22 | + jest.spyOn(fs, 'openSync').mockReturnValue(0); |
| 23 | + jest.spyOn(fs, 'readSync').mockImplementation(() => { |
| 24 | + throw new Error('read failed'); |
| 25 | + }); |
| 26 | + const close = jest.spyOn(fs, 'closeSync').mockImplementation(() => {}); |
| 27 | + |
| 28 | + expect(readShebang('command')).toBe(null); |
| 29 | + expect(close).toHaveBeenCalledTimes(1); |
| 30 | + expect(close).toHaveBeenCalledWith(0); |
| 31 | + }); |
| 32 | + |
| 33 | + it('should close the file descriptor when the file is a directory', () => { |
| 34 | + const open = jest.spyOn(fs, 'openSync'); |
| 35 | + const close = jest.spyOn(fs, 'closeSync'); |
| 36 | + |
| 37 | + expect(readShebang(__dirname)).toBe(null); |
| 38 | + |
| 39 | + // Opening a directory fails on Windows, but succeeds on other platforms and then reading fails |
| 40 | + expect(close).toHaveBeenCalledTimes(open.mock.results.filter((result) => result.type === 'return').length); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should not close a file descriptor when opening fails', () => { |
| 44 | + jest.spyOn(fs, 'openSync').mockImplementation(() => { |
| 45 | + throw new Error('open failed'); |
| 46 | + }); |
| 47 | + const close = jest.spyOn(fs, 'closeSync').mockImplementation(() => {}); |
| 48 | + |
| 49 | + expect(readShebang('command')).toBe(null); |
| 50 | + expect(close).not.toHaveBeenCalled(); |
| 51 | + }); |
| 52 | + |
| 53 | + it('should return null when closing also fails', () => { |
| 54 | + jest.spyOn(fs, 'openSync').mockReturnValue(0); |
| 55 | + jest.spyOn(fs, 'readSync').mockImplementation(() => { |
| 56 | + throw new Error('read failed'); |
| 57 | + }); |
| 58 | + jest.spyOn(fs, 'closeSync').mockImplementation(() => { |
| 59 | + throw new Error('close failed'); |
| 60 | + }); |
| 61 | + |
| 62 | + expect(readShebang('command')).toBe(null); |
| 63 | + }); |
| 64 | +}); |
0 commit comments