import { describe, it, expect, vi, beforeEach } from 'vitest' // Mock logger vi.mock('@adonisjs/core/services/logger', () => ({ default: { info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }, })) // Mock DeviceModel vi.mock('../../../../app/models/device.js', () => ({ default: { createOrUpdate: vi.fn().mockResolvedValue({}), findByDeviceId: vi.fn().mockResolvedValue(null), updateOne: vi.fn().mockResolvedValue({}), }, })) // Mock CommandModel vi.mock('../../../../app/models/command.js', () => ({ default: { getCollection: vi.fn().mockReturnValue({ find: vi.fn().mockReturnValue({ sort: vi.fn().mockReturnValue({ toArray: vi.fn().mockResolvedValue([]) }) }), countDocuments: vi.fn().mockResolvedValue(0), }), updateCommand: vi.fn().mockResolvedValue({}), }, })) import { ImmediateCommandStateMachine } from '../../../../app/services/cwmp/immediate_command_state_machine.js' import { Device } from '../../../../app/domain/device/device.js' import { DeviceId } from '../../../../app/domain/device/device_id.js' import { CWMPTaskQueue } from '../../../../app/services/cwmp/task_queue.js' function makeDevice(): Device { const device = new Device(new DeviceId('Sagemcom', 'F8B7FF', 'Livebox 4', 'LB4-TEST-001')) device.setDataModel('tr-181') return device } describe('ImmediateCommandStateMachine', () => { beforeEach(() => { vi.clearAllMocks() }) it('starts and returns empty when no commands', async () => { const device = makeDevice() const taskQueue = new CWMPTaskQueue() const sm = new ImmediateCommandStateMachine(device, 'sess-1', taskQueue) const response = await sm.start() expect(response).toBe('') // After start with no commands, the state machine finishes executing // isCompleted() checks name includes 'completed', 'operational', or 'partial_operational' // With no commands and includeNI=false, it returns isComplete=true from execute() }) it('getCurrentStateName returns executing-commands', () => { const device = makeDevice() const taskQueue = new CWMPTaskQueue() const sm = new ImmediateCommandStateMachine(device, 'sess-2', taskQueue) expect(sm.getCurrentStateName()).toBe('executing-commands') }) it('handleResponse processes message and returns result', async () => { const device = makeDevice() const taskQueue = new CWMPTaskQueue() const sm = new ImmediateCommandStateMachine(device, 'sess-3', taskQueue) // Start first await sm.start() // Handle a response after completion const response = await sm.handleResponse(true, { data: 'test' }) expect(response).toBe('') }) it('isCompleted returns false initially before start', () => { const device = makeDevice() const taskQueue = new CWMPTaskQueue() const sm = new ImmediateCommandStateMachine(device, 'sess-4', taskQueue) // Before start, ExecutingCommandsState hasn't been handled yet expect(sm.isCompleted()).toBe(false) }) })