shell.handlers.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { beforeEach, describe, expect, it, vi } from 'vitest'
  2. import * as fs from 'fs'
  3. import * as os from 'os'
  4. import * as path from 'path'
  5. import { IpcChannels } from '@shared/ipc-channels'
  6. const handlers = new Map<string, (...args: unknown[]) => Promise<{ ok: boolean; error?: string }>>()
  7. const openPath = vi.fn<(p: string) => Promise<string>>(async () => '')
  8. const openExternal = vi.fn<(u: string) => Promise<void>>(async () => {})
  9. vi.mock('electron', () => ({
  10. ipcMain: { handle: (channel: string, fn: never) => handlers.set(channel, fn) },
  11. shell: { openPath: (p: string) => openPath(p), openExternal: (u: string) => openExternal(u), showItemInFolder: vi.fn<(p: string) => void>() }
  12. }))
  13. const { registerShellHandlers } = await import('./shell.handlers')
  14. function call(channel: string, ...args: unknown[]) {
  15. return handlers.get(channel)!({}, ...args)
  16. }
  17. describe('shell handlers', () => {
  18. const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wem-shell-'))
  19. beforeEach(() => {
  20. handlers.clear()
  21. openPath.mockClear()
  22. openExternal.mockClear()
  23. registerShellHandlers()
  24. })
  25. it('opens an existing folder', async () => {
  26. expect(await call(IpcChannels.SHELL_OPEN_PATH, dir)).toEqual({ ok: true, error: undefined })
  27. expect(openPath).toHaveBeenCalledWith(dir)
  28. })
  29. it('does not hand a missing path or a non-string to the opener', async () => {
  30. expect((await call(IpcChannels.SHELL_OPEN_PATH, path.join(dir, 'nope'))).ok).toBe(false)
  31. expect((await call(IpcChannels.SHELL_OPEN_PATH, '')).ok).toBe(false)
  32. expect((await call(IpcChannels.SHELL_OPEN_PATH, { toString: () => dir })).ok).toBe(false)
  33. expect(openPath).not.toHaveBeenCalled()
  34. })
  35. it('opens only safe links', async () => {
  36. expect((await call(IpcChannels.SHELL_OPEN_EXTERNAL, 'file:///etc/passwd')).ok).toBe(false)
  37. expect((await call(IpcChannels.SHELL_OPEN_EXTERNAL, 'https://example.org')).ok).toBe(true)
  38. expect(openExternal).toHaveBeenCalledTimes(1)
  39. })
  40. })