|
| 1 | +import { fork } from 'node:child_process'; |
| 2 | +import { type Readable } from 'node:stream'; |
| 3 | +import { describe, it, expect, vi } from 'vitest'; |
| 4 | + |
| 5 | +import { PluginProcess, returnMessageCmd } from '../../src/plugins/plugin-process.js'; |
| 6 | +import { MessageCmd, MessageStatus, SpawnStatus } from 'codify-schemas'; |
| 7 | +import { ctx } from '../../src/events/context.js'; |
| 8 | + |
| 9 | +vi.mock('node:child_process', async () => {n |
| 10 | + const { ChildProcess } = await import('node:child_process'); |
| 11 | + const { default: EventEmitter } = await import('node:events'); |
| 12 | + |
| 13 | + const process = new ChildProcess(); |
| 14 | + process.stdout = new EventEmitter() as Readable; |
| 15 | + process.stderr = new EventEmitter() as Readable |
| 16 | + process.send = () => true; |
| 17 | + |
| 18 | + return { fork: () => process }; |
| 19 | +}) |
| 20 | + |
| 21 | +describe('Message sender tests', async () => { |
| 22 | + it('Is able to send a message and await a result', async () => { |
| 23 | + // Uses the child process from the mocks |
| 24 | + const mockChildProcess = fork(''); |
| 25 | + |
| 26 | + const sudoRequestedSpy = vi.spyOn(ctx, 'sudoRequested'); |
| 27 | + const processSpy = vi.spyOn(mockChildProcess, 'send'); |
| 28 | + |
| 29 | + const plugin = await PluginProcess.start('', 'TestPlugin', false); |
| 30 | + |
| 31 | + mockChildProcess.emit('message', { cmd: MessageCmd.SUDO_REQUEST, data: { command: 'sudo something' }, requestId: 'requestId' }) |
| 32 | + expect(sudoRequestedSpy).toHaveBeenCalledOnce(); |
| 33 | + |
| 34 | + ctx.sudoRequestGranted('TestPlugin', { status: SpawnStatus.SUCCESS, data: 'success' }) |
| 35 | + expect(processSpy).to.be.lastCalledWith({ |
| 36 | + cmd: returnMessageCmd(MessageCmd.SUDO_REQUEST), |
| 37 | + requestId: 'requestId', |
| 38 | + data: expect.objectContaining({ |
| 39 | + status: MessageStatus.SUCCESS, |
| 40 | + data: 'success', |
| 41 | + }) |
| 42 | + }); |
| 43 | + }) |
| 44 | +}); |
0 commit comments