|
| 1 | +/* eslint-disable no-restricted-imports */ |
| 2 | +import {treeKill} from './tree-kill.js' |
| 3 | +import {vi, describe, test, expect, afterEach} from 'vitest' |
| 4 | +import {spawn} from 'child_process' |
| 5 | + |
| 6 | +vi.mock('child_process', async () => { |
| 7 | + const actual: any = await vi.importActual('child_process') |
| 8 | + return { |
| 9 | + ...actual, |
| 10 | + spawn: vi.fn(), |
| 11 | + } |
| 12 | +}) |
| 13 | + |
| 14 | +describe('treeKill', () => { |
| 15 | + afterEach(() => { |
| 16 | + vi.unstubAllGlobals() |
| 17 | + }) |
| 18 | + |
| 19 | + test('calls the callback with an error if the PID is not a number (string with digits)', async () => { |
| 20 | + const maliciousPid = '1234; calc.exe' |
| 21 | + |
| 22 | + await new Promise<void>((resolve) => { |
| 23 | + // Correct signature for treeKill is (pid, signal, killRoot, callback) |
| 24 | + treeKill(maliciousPid, 'SIGTERM', true, (err) => { |
| 25 | + expect(err?.message).toBe('pid must be a number') |
| 26 | + resolve() |
| 27 | + }) |
| 28 | + }) |
| 29 | + |
| 30 | + expect(spawn).not.toHaveBeenCalled() |
| 31 | + }) |
| 32 | + |
| 33 | + test('works with a valid numeric PID as string', () => { |
| 34 | + const pid = '1234' |
| 35 | + vi.mocked(spawn).mockReturnValue({ |
| 36 | + on: vi.fn(), |
| 37 | + stdout: {on: vi.fn()}, |
| 38 | + } as any) |
| 39 | + vi.stubGlobal('process', {...process, platform: 'win32'}) |
| 40 | + |
| 41 | + treeKill(pid) |
| 42 | + |
| 43 | + expect(spawn).toHaveBeenCalledWith('taskkill', ['/pid', '1234', '/T', '/F']) |
| 44 | + }) |
| 45 | + |
| 46 | + test('works with a valid numeric PID as number', () => { |
| 47 | + const pid = 1234 |
| 48 | + vi.mocked(spawn).mockReturnValue({ |
| 49 | + on: vi.fn(), |
| 50 | + stdout: {on: vi.fn()}, |
| 51 | + } as any) |
| 52 | + vi.stubGlobal('process', {...process, platform: 'win32'}) |
| 53 | + |
| 54 | + treeKill(pid) |
| 55 | + |
| 56 | + expect(spawn).toHaveBeenCalledWith('taskkill', ['/pid', '1234', '/T', '/F']) |
| 57 | + }) |
| 58 | +}) |
0 commit comments