feat(V2-1a): Monorepo 구조 전환 — apps/desktop으로 V1 이동

- npm workspaces 루트 (apps/*, packages/*) 세팅
- V1 전체를 apps/desktop/으로 git mv (src, resources, tests, sidecar,
  scripts, electron.vite.config.ts, electron-builder.yml, vitest.config.ts,
  tsconfig.node.json, tsconfig.web.json)
- apps/desktop/package.json 신규 (name=@d3ro/desktop)
- productName: 'd3ro-voice' 명시 — app.getName()을 고정하여 userData 경로
  %APPDATA%\d3ro-voice\ 그대로 유지 (기존 DB/설정 연속성 보장)
- 루트 package.json을 workspace 루트로 재구성, 공통 devDep만 유지
  (typescript, eslint, prettier)
- turbo.json, tsconfig.base.json 추가 (Turborepo 자체 설치는 별도 sub-phase)
- memory/project_status.md 생성 (규칙 13)

검증:
- npm run typecheck 통과
- npm run build 통과 (electron-vite main+preload+renderer)
- npm run dev 실제 실행 → DB/핫키/Ollama 자동 실행 모두 정상
This commit is contained in:
yunchan8804 2026-04-08 14:04:41 +09:00
parent 3a160b9032
commit 45a580878a
178 changed files with 214 additions and 0 deletions

View file

@ -1,87 +0,0 @@
// tests/helpers/createTestDb.ts
// in-memory SQLite + drizzle-orm 스키마 적용
import Database from 'better-sqlite3'
import { drizzle, type BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
import * as schema from '../../src/main/db/schema'
/**
* in-memory SQLite DB를 .
* DB를 .
*/
export function createTestDb(): {
db: BetterSQLite3Database<typeof schema>
sqlite: Database.Database
close: () => void
} {
const sqlite = new Database(':memory:')
sqlite.pragma('journal_mode = WAL')
sqlite.pragma('foreign_keys = ON')
// 테이블 생성 (src/main/db/index.ts의 SQL과 동일)
sqlite.exec(`
CREATE TABLE IF NOT EXISTS history (
id TEXT PRIMARY KEY,
original_text TEXT NOT NULL,
polished_text TEXT,
focused_app TEXT,
focused_app_name TEXT,
focused_app_window_title TEXT,
mode TEXT NOT NULL DEFAULT 'dictation',
status TEXT NOT NULL DEFAULT 'completed',
error_code TEXT,
audio_local_path TEXT,
duration REAL NOT NULL,
detected_language TEXT,
mic_device TEXT,
word_count INTEGER NOT NULL DEFAULT 0,
stt_model TEXT,
llm_model TEXT,
stt_latency_ms INTEGER,
llm_latency_ms INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
app_version TEXT NOT NULL DEFAULT '1.0.0'
);
CREATE INDEX IF NOT EXISTS idx_history_created_at ON history(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_history_status ON history(status);
CREATE TABLE IF NOT EXISTS dictionary (
id TEXT PRIMARY KEY,
word TEXT NOT NULL,
pronunciation TEXT,
category TEXT NOT NULL DEFAULT 'user',
usage_count INTEGER NOT NULL DEFAULT 0,
last_used_at INTEGER,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_dictionary_word_category ON dictionary(word, category);
CREATE INDEX IF NOT EXISTS idx_dictionary_created_at ON dictionary(created_at);
CREATE INDEX IF NOT EXISTS idx_dictionary_usage_count ON dictionary(usage_count DESC);
CREATE TABLE IF NOT EXISTS stats (
id INTEGER PRIMARY KEY CHECK (id = 1),
total_duration REAL NOT NULL DEFAULT 0,
total_words INTEGER NOT NULL DEFAULT 0,
session_count INTEGER NOT NULL DEFAULT 0,
streak_days INTEGER NOT NULL DEFAULT 0,
last_session_at INTEGER,
last_updated INTEGER NOT NULL
);
INSERT OR IGNORE INTO stats (id, total_duration, total_words, session_count, streak_days, last_updated)
VALUES (1, 0, 0, 0, 0, ${Date.now()});
`)
const db = drizzle(sqlite, { schema })
return {
db,
sqlite,
close: () => sqlite.close()
}
}

View file

@ -1,190 +0,0 @@
// tests/main/services/CustomInstructionService.test.ts
// CRUD + 프리셋 보호 + 순서 변경 테스트
import { describe, it, expect, beforeEach, vi } from 'vitest'
// ConfigService 모킹
const mockStore: Record<string, unknown> = {}
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: string) => mockStore[key]),
configSet: vi.fn((key: string, value: unknown) => {
mockStore[key] = value
})
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn()
})
}))
let getCustomInstructionService: () => ReturnType<typeof import('../../../src/main/services/CustomInstructionService')['getCustomInstructionService']>
beforeEach(async () => {
// 매번 모듈과 스토어 초기화
for (const key of Object.keys(mockStore)) {
delete mockStore[key]
}
vi.resetModules()
const mod = await import('../../../src/main/services/CustomInstructionService')
getCustomInstructionService = mod.getCustomInstructionService
})
describe('CustomInstructionService', () => {
describe('initialize + getAll', () => {
it('첫 실행 시 5개 프리셋이 생성된다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const all = svc.getAll()
expect(all.length).toBe(5)
expect(all.every((i) => i.isBuiltin)).toBe(true)
})
it('order 순으로 정렬하여 반환한다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const all = svc.getAll()
for (let i = 1; i < all.length; i++) {
expect(all[i].order).toBeGreaterThanOrEqual(all[i - 1].order)
}
})
})
describe('getById', () => {
it('존재하는 ID로 명령어를 반환한다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const inst = svc.getById('builtin-translate')
expect(inst).not.toBeNull()
expect(inst!.name).toBe('번역')
})
it('없는 ID에 대해 null을 반환한다', () => {
const svc = getCustomInstructionService()
svc.initialize()
expect(svc.getById('nonexistent')).toBeNull()
})
})
describe('create', () => {
it('사용자 정의 명령어를 추가한다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const created = svc.create({
name: 'My Custom',
description: 'Test custom instruction',
prompt: 'Custom prompt: {{text}}',
icon: 'Star'
})
expect(created.isBuiltin).toBe(false)
expect(created.name).toBe('My Custom')
expect(svc.getAll().length).toBe(6)
})
})
describe('update', () => {
it('사용자 정의 명령어의 모든 필드를 수정할 수 있다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const created = svc.create({
name: 'Original',
description: 'Desc',
prompt: 'Prompt',
icon: 'Star'
})
const updated = svc.update(created.id, { name: 'Updated', prompt: 'New prompt' })
expect(updated).not.toBeNull()
expect(updated!.name).toBe('Updated')
expect(updated!.prompt).toBe('New prompt')
})
it('프리셋은 프롬프트만 수정 가능하다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const updated = svc.update('builtin-translate', { name: 'Changed Name', prompt: 'New prompt' })
expect(updated).not.toBeNull()
expect(updated!.name).toBe('번역') // 이름은 변경 안 됨
expect(updated!.prompt).toBe('New prompt') // 프롬프트는 변경됨
})
})
describe('delete', () => {
it('프리셋은 삭제할 수 없다', () => {
const svc = getCustomInstructionService()
svc.initialize()
expect(svc.delete('builtin-translate')).toBe(false)
expect(svc.getAll().length).toBe(5)
})
it('사용자 정의 명령어는 삭제할 수 있다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const created = svc.create({
name: 'To Delete',
description: '',
prompt: '',
icon: ''
})
expect(svc.delete(created.id)).toBe(true)
expect(svc.getAll().length).toBe(5)
})
it('없는 ID 삭제 시 false를 반환한다', () => {
const svc = getCustomInstructionService()
svc.initialize()
expect(svc.delete('nonexistent')).toBe(false)
})
})
describe('reorder', () => {
it('지정된 순서대로 order를 재설정한다', () => {
const svc = getCustomInstructionService()
svc.initialize()
const all = svc.getAll()
const reversed = [...all].reverse().map((i) => i.id)
svc.reorder(reversed)
const reordered = svc.getAll()
expect(reordered[0].id).toBe(reversed[0])
expect(reordered[4].id).toBe(reversed[4])
})
})
describe('resetBuiltins', () => {
it('프리셋을 초기값으로 복원하고 사용자 명령어는 유지한다', () => {
const svc = getCustomInstructionService()
svc.initialize()
// 프롬프트 수정
svc.update('builtin-translate', { prompt: 'modified prompt' })
// 사용자 명령어 추가
svc.create({ name: 'User', description: '', prompt: '', icon: '' })
svc.resetBuiltins()
const all = svc.getAll()
const translate = all.find((i) => i.id === 'builtin-translate')
expect(translate!.prompt).toContain('{{targetLanguage}}') // 원래 프롬프트
expect(all.length).toBe(6) // 프리셋 5 + 사용자 1
})
})
})

View file

@ -1,116 +0,0 @@
// tests/main/services/DictionaryService.test.ts
// DictionaryService 단위 테스트 — DB 모킹
import { describe, it, expect, beforeEach, vi } from 'vitest'
function createMockQueryBuilder(data: unknown[] = []) {
const builder: Record<string, unknown> = {}
builder.values = vi.fn(() => ({ run: vi.fn(() => ({ changes: 1 })) }))
builder.from = vi.fn(() => builder)
builder.where = vi.fn(() => builder)
builder.orderBy = vi.fn(() => builder)
builder.limit = vi.fn(() => builder)
builder.offset = vi.fn(() => builder)
builder.set = vi.fn(() => builder)
builder.get = vi.fn(() => data[0] ?? null)
builder.all = vi.fn(() => data)
builder.run = vi.fn(() => ({ changes: 1 }))
return builder
}
const mockDb = {
insert: vi.fn(() => createMockQueryBuilder()),
select: vi.fn(() => createMockQueryBuilder()),
update: vi.fn(() => createMockQueryBuilder()),
delete: vi.fn(() => createMockQueryBuilder())
}
vi.mock('../../../src/main/db', () => ({
getDatabase: () => mockDb
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn()
})
}))
let getDictionaryService: () => ReturnType<typeof import('../../../src/main/services/DictionaryService')['getDictionaryService']>
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
const mod = await import('../../../src/main/services/DictionaryService')
getDictionaryService = mod.getDictionaryService
})
describe('DictionaryService', () => {
describe('add', () => {
it('insert를 호출하고 엔트리를 반환한다', () => {
const svc = getDictionaryService()
const entry = svc.add({ word: 'AI', pronunciation: '에이아이', category: 'technical' })
expect(mockDb.insert).toHaveBeenCalled()
expect(entry.id).toBeDefined()
expect(entry.word).toBe('AI')
expect(entry.pronunciation).toBe('에이아이')
expect(entry.category).toBe('technical')
expect(entry.usageCount).toBe(0)
})
it('기본 카테고리는 user이다', () => {
const svc = getDictionaryService()
const entry = svc.add({ word: '테스트' })
expect(entry.category).toBe('user')
})
it('pronunciation 미지정 시 null이다', () => {
const svc = getDictionaryService()
const entry = svc.add({ word: 'test' })
expect(entry.pronunciation).toBeNull()
})
})
describe('update', () => {
it('없는 ID에 대해 null을 반환한다', () => {
// select().from().where().get()이 null 반환
const svc = getDictionaryService()
expect(svc.update({ id: 'nonexistent', word: 'test' })).toBeNull()
})
})
describe('delete', () => {
it('delete 쿼리를 실행하고 changes > 0이면 true를 반환한다', () => {
const svc = getDictionaryService()
expect(svc.delete('some-id')).toBe(true)
expect(mockDb.delete).toHaveBeenCalled()
})
})
describe('incrementUsage', () => {
it('update 쿼리를 실행한다', () => {
const svc = getDictionaryService()
svc.incrementUsage('some-id')
expect(mockDb.update).toHaveBeenCalled()
})
})
describe('getPromptHints', () => {
it('빈 목록에서 빈 문자열을 반환한다', () => {
const svc = getDictionaryService()
expect(svc.getPromptHints()).toBe('')
})
})
describe('dispose', () => {
it('에러 없이 호출된다', () => {
const svc = getDictionaryService()
expect(() => svc.dispose()).not.toThrow()
})
})
})

View file

@ -1,134 +0,0 @@
// tests/main/services/HistoryService.test.ts
// HistoryService 단위 테스트 — DB 계층을 모킹하여 순수 로직만 검증
import { describe, it, expect, beforeEach, vi } from 'vitest'
// drizzle 모킹: 체이너블 쿼리 빌더 패턴
function createMockQueryBuilder(data: unknown[] = []) {
const builder: Record<string, unknown> = {}
builder.values = vi.fn(() => ({ run: vi.fn(() => ({ changes: 1 })) }))
builder.from = vi.fn(() => builder)
builder.where = vi.fn(() => builder)
builder.orderBy = vi.fn(() => builder)
builder.limit = vi.fn(() => builder)
builder.offset = vi.fn(() => builder)
builder.set = vi.fn(() => builder)
builder.get = vi.fn(() => data[0] ?? null)
builder.all = vi.fn(() => data)
builder.run = vi.fn(() => ({ changes: 1 }))
return builder
}
const mockDb = {
insert: vi.fn(() => createMockQueryBuilder()),
select: vi.fn(() => createMockQueryBuilder()),
update: vi.fn(() => createMockQueryBuilder()),
delete: vi.fn(() => createMockQueryBuilder())
}
vi.mock('../../../src/main/db', () => ({
getDatabase: () => mockDb
}))
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn()
})
}))
let getHistoryService: () => ReturnType<typeof import('../../../src/main/services/HistoryService')['getHistoryService']>
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
const mod = await import('../../../src/main/services/HistoryService')
getHistoryService = mod.getHistoryService
})
describe('HistoryService', () => {
describe('create', () => {
it('insert를 호출하고 엔트리를 반환한다', () => {
const svc = getHistoryService()
const entry = svc.create({
originalText: '안녕하세요',
duration: 3.5,
wordCount: 3,
mode: 'dictation',
status: 'completed',
appVersion: '1.0.0'
})
expect(mockDb.insert).toHaveBeenCalled()
expect(entry.id).toBeDefined()
expect(entry.originalText).toBe('안녕하세요')
expect(entry.duration).toBe(3.5)
expect(entry.createdAt).toBeGreaterThan(0)
})
it('stats 업데이트를 호출한다', () => {
const svc = getHistoryService()
svc.create({
originalText: 'test',
duration: 5.0,
wordCount: 10,
mode: 'dictation',
status: 'completed',
appVersion: '1.0.0'
})
// insert 2번: history + stats update
expect(mockDb.insert).toHaveBeenCalledTimes(1)
expect(mockDb.update).toHaveBeenCalledTimes(1) // stats update
})
})
describe('getById', () => {
it('DB에서 조회한 결과를 반환한다', () => {
// select().from().where().get()이 null 반환하면 null
const svc = getHistoryService()
const result = svc.getById('nonexistent')
expect(result).toBeNull()
})
})
describe('delete', () => {
it('delete 쿼리를 실행하고 changes > 0이면 true를 반환한다', () => {
const svc = getHistoryService()
const result = svc.delete('some-id')
expect(mockDb.delete).toHaveBeenCalled()
expect(result).toBe(true)
})
})
describe('deleteAll', () => {
it('delete 쿼리를 실행한다', () => {
const svc = getHistoryService()
svc.deleteAll()
expect(mockDb.delete).toHaveBeenCalled()
})
})
describe('getStats', () => {
it('stats + today 쿼리를 실행한다', () => {
const svc = getHistoryService()
const st = svc.getStats()
expect(mockDb.select).toHaveBeenCalled()
expect(st).toHaveProperty('totalRecordingTimeMs')
expect(st).toHaveProperty('todaySessionCount')
expect(st).toHaveProperty('streakDays')
})
})
describe('dispose', () => {
it('에러 없이 호출된다', () => {
const svc = getHistoryService()
expect(() => svc.dispose()).not.toThrow()
})
})
})

View file

@ -1,202 +0,0 @@
// tests/main/services/VoiceModeService.test.ts
// 상태 머신 전이 + 이중 조건 플러시 + accidentalPress 테스트
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { RecognitionState, AudioState } from '../../../src/shared/types'
import { TIMING } from '../../../src/shared/constants'
// 모든 하위 서비스 모킹
vi.mock('../../../src/main/services/LoggerService', () => ({
getLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn()
})
}))
const mockSTT = {
initialize: vi.fn(() => Promise.resolve()),
transcribe: vi.fn(() =>
Promise.resolve({ text: '테스트 전사', segments: [], language: 'ko', duration: 2, processingTime: 500 })
),
getStatus: vi.fn(() => ({ state: 'ready', modelId: 'base', uptime: 0 })),
on: vi.fn(),
off: vi.fn()
}
vi.mock('../../../src/main/services/LocalSTTService', () => ({
getLocalSTTService: () => mockSTT
}))
const mockAudio = {
start: vi.fn(() => Promise.resolve()),
stop: vi.fn(() => Promise.resolve()),
on: vi.fn(),
off: vi.fn()
}
vi.mock('../../../src/main/services/AudioCaptureService', () => ({
getAudioCaptureService: () => mockAudio
}))
const mockHotkey = {
on: vi.fn(),
off: vi.fn()
}
vi.mock('../../../src/main/services/HotkeyService', () => ({
getHotkeyService: () => mockHotkey
}))
vi.mock('../../../src/main/services/ConfigService', () => ({
configGet: vi.fn((key: string) => {
const defaults: Record<string, unknown> = {
sttModelId: 'base',
defaultLLMAction: 'refine',
ollamaServerUrl: 'http://localhost:11434',
llmModelId: 'qwen3:4b'
}
return defaults[key]
})
}))
const mockTextInsert = {
insertText: vi.fn(() => Promise.resolve({ success: true, method: 'clipboard', textLength: 10, durationMs: 50 }))
}
vi.mock('../../../src/main/services/TextInsertService', () => ({
getTextInsertService: () => mockTextInsert
}))
const mockLLM = {
isAvailable: vi.fn(() => false),
processText: vi.fn(() => Promise.resolve('다듬어진 텍스트')),
on: vi.fn(),
off: vi.fn()
}
vi.mock('../../../src/main/services/LocalLLMService', () => ({
getLocalLLMService: () => mockLLM
}))
let getVoiceModeService: () => ReturnType<typeof import('../../../src/main/services/VoiceModeService')['getVoiceModeService']>
beforeEach(async () => {
vi.resetModules()
vi.clearAllMocks()
const mod = await import('../../../src/main/services/VoiceModeService')
getVoiceModeService = mod.getVoiceModeService
})
describe('VoiceModeService', () => {
describe('상태 머신', () => {
it('초기 상태는 IDLE이다', () => {
const svc = getVoiceModeService()
const state = svc.getState()
expect(state.recognitionState).toBe(RecognitionState.IDLE)
expect(state.audioState).toBe(AudioState.IDLE)
expect(state.sessionId).toBeNull()
})
it('startSession 호출 시 PREPARING으로 전이한다', async () => {
const svc = getVoiceModeService()
const stateChanges: RecognitionState[] = []
svc.on('recognition-state-changed', (payload: { current: RecognitionState }) => {
stateChanges.push(payload.current)
})
await svc.startSession('dictation')
// PREPARING → CONNECTING → READY 순서
expect(stateChanges[0]).toBe(RecognitionState.PREPARING)
expect(stateChanges).toContain(RecognitionState.CONNECTING)
})
it('isActive는 세션이 활성일 때 true이다', async () => {
const svc = getVoiceModeService()
expect(svc.isActive).toBe(false)
// startSession은 완전 비동기이므로 await 후 세션 활성 확인
await svc.startSession('dictation')
expect(svc.isActive).toBe(true)
})
})
describe('accidentalPress', () => {
it('700ms 미만 세션은 자동 취소된다', async () => {
const svc = getVoiceModeService()
let cancelReason: string | null = null
svc.on('session-cancelled', (payload: { reason: string }) => {
cancelReason = payload.reason
})
// 세션 시작 즉시 종료 (700ms 미만)
await svc.startSession('dictation')
await svc.stopSession()
expect(cancelReason).toBe('too-short')
})
})
describe('cancelSession', () => {
it('user 취소로 세션을 종료한다', async () => {
const svc = getVoiceModeService()
let cancelReason: string | null = null
svc.on('session-cancelled', (payload: { reason: string }) => {
cancelReason = payload.reason
})
await svc.startSession('dictation')
svc.cancelSession()
expect(cancelReason).toBe('user')
})
})
describe('getState', () => {
it('현재 상태를 VoiceState 형태로 반환한다', () => {
const svc = getVoiceModeService()
const state = svc.getState()
expect(state).toHaveProperty('recognitionState')
expect(state).toHaveProperty('audioState')
expect(state).toHaveProperty('mode')
expect(state).toHaveProperty('sessionId')
expect(state).toHaveProperty('recordingStartedAt')
})
})
describe('터미널 상태', () => {
it('cancelSession 후 _resetToIdle의 200ms 딜레이 후 IDLE로 전이한다', async () => {
vi.useFakeTimers()
const svc = getVoiceModeService()
await svc.startSession('dictation')
svc.cancelSession()
// 200ms 딜레이로 IDLE 전이 예약됨
vi.advanceTimersByTime(250)
const state = svc.getState()
expect(state.recognitionState).toBe(RecognitionState.IDLE)
vi.useRealTimers()
})
})
})
describe('TIMING 상수', () => {
it('핵심 타이밍 값이 Speakly 패턴과 일치한다', () => {
expect(TIMING.MIN_AUDIO_DURATION).toBe(700)
expect(TIMING.DOUBLE_PRESS_DURATION).toBe(300)
expect(TIMING.POST_RECORDING_WAIT).toBe(4000)
expect(TIMING.POST_RECORDING_WAIT_BUFFERED).toBe(6000)
expect(TIMING.ABSOLUTE_MAX_WAIT).toBe(120000)
expect(TIMING.AUDIO_LEVEL_INTERVAL).toBe(100)
})
})

View file

@ -1,73 +0,0 @@
// tests/setup.ts
// vitest 글로벌 셋업: electron 모듈 모킹
import { vi } from 'vitest'
// electron 모듈 모킹 — 테스트에서 electron import 시 에러 방지
vi.mock('electron', () => ({
app: {
getPath: vi.fn(() => ':memory:'),
getVersion: vi.fn(() => '1.0.0'),
quit: vi.fn(),
on: vi.fn(),
whenReady: vi.fn(() => Promise.resolve())
},
ipcMain: {
handle: vi.fn(),
on: vi.fn(),
removeHandler: vi.fn()
},
BrowserWindow: vi.fn(),
Tray: vi.fn(),
Menu: vi.fn(),
nativeImage: {
createFromPath: vi.fn()
},
dialog: {
showErrorBox: vi.fn()
},
screen: {
getPrimaryDisplay: vi.fn(() => ({
workArea: { x: 0, y: 0, width: 1920, height: 1080 }
}))
},
clipboard: {
readText: vi.fn(() => ''),
writeText: vi.fn(),
readHTML: vi.fn(() => ''),
readRTF: vi.fn(() => ''),
readImage: vi.fn(() => ({ isEmpty: () => true, toPNG: () => Buffer.alloc(0) })),
write: vi.fn()
}
}))
// WindowManager 모킹 — VoiceModeService가 import하므로 필요
vi.mock('../src/main/windows/WindowManager', () => ({
showRecordingTip: vi.fn(),
hideRecordingTip: vi.fn(),
updateRecordingTipState: vi.fn(),
sendAudioLevelToTip: vi.fn(),
showResultPopup: vi.fn(),
hideResultPopup: vi.fn(),
getMainWindow: vi.fn(),
createMainWindow: vi.fn(),
}))
// electron-log 모킹
vi.mock('electron-log', () => {
const noop = vi.fn()
return {
default: {
info: noop,
warn: noop,
error: noop,
debug: noop,
create: () => ({
info: noop,
warn: noop,
error: noop,
debug: noop
})
}
}
})

View file

@ -1,75 +0,0 @@
// tests/shared/errors.test.ts
// D3ROError + IPCResult 헬퍼 테스트
import { describe, it, expect } from 'vitest'
import { D3ROError, ErrorCode, ipcSuccess, ipcError } from '../../src/shared/errors'
describe('D3ROError', () => {
it('code, message, details를 올바르게 설정한다', () => {
const err = new D3ROError(ErrorCode.STTModelNotFound, 'Model not found', { modelId: 'large' })
expect(err.code).toBe(ErrorCode.STTModelNotFound)
expect(err.message).toBe('Model not found')
expect(err.details).toEqual({ modelId: 'large' })
expect(err.name).toBe('D3ROError')
expect(err instanceof Error).toBe(true)
})
it('toJSON으로 직렬화할 수 있다', () => {
const err = new D3ROError(ErrorCode.LLMServerUnreachable, 'Server down')
const json = err.toJSON()
expect(json.code).toBe(300)
expect(json.message).toBe('Server down')
expect(json.details).toBeUndefined()
})
it('fromJSON으로 역직렬화할 수 있다', () => {
const json = { code: ErrorCode.AudioDeviceNotFound, message: 'No mic' }
const err = D3ROError.fromJSON(json)
expect(err).toBeInstanceOf(D3ROError)
expect(err.code).toBe(ErrorCode.AudioDeviceNotFound)
expect(err.message).toBe('No mic')
})
})
describe('IPCResult helpers', () => {
it('ipcSuccess는 success: true + data를 반환한다', () => {
const result = ipcSuccess({ value: 42 })
expect(result.success).toBe(true)
if (result.success) {
expect(result.data).toEqual({ value: 42 })
}
})
it('ipcError는 success: false + error를 반환한다', () => {
const result = ipcError(ErrorCode.DBQueryFailed, 'Query failed', { table: 'history' })
expect(result.success).toBe(false)
if (!result.success) {
expect(result.error.code).toBe(ErrorCode.DBQueryFailed)
expect(result.error.message).toBe('Query failed')
expect(result.error.details).toEqual({ table: 'history' })
}
})
})
describe('ErrorCode', () => {
it('에러 코드 범위가 올바르다', () => {
// STT: 100-199
expect(ErrorCode.STTEngineNotInstalled).toBe(100)
expect(ErrorCode.STTGPUNotAvailable).toBe(140)
// LLM: 300-399
expect(ErrorCode.LLMServerUnreachable).toBe(300)
expect(ErrorCode.LLMPromptTooLong).toBe(331)
// Audio: 400-499
expect(ErrorCode.AudioDeviceNotFound).toBe(400)
// System: 900-999
expect(ErrorCode.UnknownError).toBe(999)
})
})