d3ro-voice/apps/desktop/tests/main/services/win32-input-activity.test.ts

77 lines
2.8 KiB
TypeScript

import { createRequire } from 'node:module'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const nodeRequire = createRequire(import.meta.url)
const koffiPath = nodeRequire.resolve('koffi')
const originalKoffi = nodeRequire.cache[koffiPath]
const nativeRead = vi.fn<(info: Buffer) => boolean>()
const load = vi.fn()
let input: typeof import('../../../src/main/utils/win32-input-activity')
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({ warn: vi.fn() })
}))
beforeEach(async () => {
vi.resetModules()
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
nativeRead.mockReset().mockImplementation((info) => {
expect(info.length).toBe(8)
expect(info.readUInt32LE(0)).toBe(8)
info.writeUInt32LE(0xfedcba98, 4)
return true
})
load.mockReset().mockReturnValue({ func: vi.fn(() => nativeRead) })
nodeRequire.cache[koffiPath] = {
id: koffiPath, filename: koffiPath, loaded: true, exports: { load }
} as unknown as NodeModule
input = await import('../../../src/main/utils/win32-input-activity')
})
afterEach(() => {
if (originalKoffi) nodeRequire.cache[koffiPath] = originalKoffi
else delete nodeRequire.cache[koffiPath]
vi.restoreAllMocks()
})
describe('native input activity token', () => {
it('initializes LASTINPUTINFO.cbSize and reads an unsigned DWORD without epoch conversion', () => {
expect(input.getLastNativeInputTick()).toBe(0xfedcba98)
expect(input.getLastNativeInputTick()).toBe(0xfedcba98)
expect(nativeRead).toHaveBeenCalledTimes(2)
expect(load).toHaveBeenCalledTimes(1)
expect(load).toHaveBeenCalledWith('user32.dll')
})
it('preserves zero after tick wraparound as a valid token', () => {
nativeRead.mockImplementation((info) => {
info.writeUInt32LE(0, 4)
return true
})
expect(input.getLastNativeInputTick()).toBe(0)
})
it('returns null on native failure instead of treating zeroed memory as an idle token', () => {
nativeRead.mockReturnValueOnce(false)
expect(input.getLastNativeInputTick()).toBeNull()
expect(input.getLastNativeInputTick()).toBe(0xfedcba98)
})
it('does not load a Windows DLL on other platforms', () => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
expect(input.getLastNativeInputTick()).toBeNull()
expect(load).not.toHaveBeenCalled()
})
it('fails closed and avoids repeated native loads when koffi is unavailable', () => {
load.mockImplementation(() => { throw new Error('unavailable') })
expect(input.getLastNativeInputTick()).toBeNull()
expect(input.getLastNativeInputTick()).toBeNull()
expect(load).toHaveBeenCalledTimes(1)
})
it('returns null when native invocation throws', () => {
nativeRead.mockImplementation(() => { throw new Error('native failure') })
expect(input.getLastNativeInputTick()).toBeNull()
})
})