| 1 | import { Logger } from '@nestjs/common' |
| 2 | import { ResponseCode } from '@yikart/common' |
| 3 | import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 4 | |
| 5 | import { ConfigRestartService } from './config-restart.service' |
| 6 | |
| 7 | const execFileMock = vi.hoisted(() => vi.fn()) |
| 8 | |
| 9 | vi.mock('node:child_process', () => ({ |
| 10 | execFile: execFileMock, |
| 11 | })) |
| 12 | |
| 13 | describe('configRestartService', () => { |
| 14 | let originalPmId: string | undefined |
| 15 | |
| 16 | beforeEach(() => { |
| 17 | originalPmId = process.env['pm_id'] |
| 18 | execFileMock.mockReset() |
| 19 | }) |
| 20 | |
| 21 | afterEach(() => { |
| 22 | if (originalPmId === undefined) |
| 23 | delete process.env['pm_id'] |
| 24 | else |
| 25 | process.env['pm_id'] = originalPmId |
| 26 | }) |
| 27 | |
| 28 | it('没有 PM2 进程 ID 时拒绝重启', () => { |
| 29 | delete process.env['pm_id'] |
| 30 | |
| 31 | expect(() => new ConfigRestartService().restart()).toThrow(expect.objectContaining({ |
| 32 | code: ResponseCode.ConfigEditorPm2Unavailable, |
| 33 | })) |
| 34 | }) |
| 35 | |
| 36 | it('通过 pm2 重启当前进程', () => { |
| 37 | process.env['pm_id'] = '7' |
| 38 | const unref = vi.fn() |
| 39 | execFileMock.mockReturnValue({ unref }) |
| 40 | |
| 41 | new ConfigRestartService().restart() |
| 42 | |
| 43 | expect(execFileMock).toHaveBeenCalledWith('pm2', ['restart', '7'], expect.any(Function)) |
| 44 | expect(unref).toHaveBeenCalled() |
| 45 | }) |
| 46 | |
| 47 | it('记录 pm2 异步重启失败', () => { |
| 48 | process.env['pm_id'] = '8' |
| 49 | const unref = vi.fn() |
| 50 | const errorSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined) |
| 51 | execFileMock.mockReturnValue({ unref }) |
| 52 | |
| 53 | new ConfigRestartService().restart() |
| 54 | const callback = execFileMock.mock.calls[0][2] as (error: Error) => void |
| 55 | callback(new Error('restart failed')) |
| 56 | |
| 57 | expect(errorSpy).toHaveBeenCalledWith(expect.any(Error)) |
| 58 | errorSpy.mockRestore() |
| 59 | }) |
| 60 | }) |
| 61 |