File size: 2,458 Bytes
40f303b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { describe, it, expect, vi, beforeEach } from 'vitest'

const { mockPragma, MockDatabase } = vi.hoisted(() => {
  const mockPragma = vi.fn()
  const MockDatabase = vi.fn(() => ({
    pragma: mockPragma,
    prepare: vi.fn(() => ({
      run: vi.fn(() => ({ lastInsertRowid: 1, changes: 1 })),
      get: vi.fn(() => ({ count: 0 })),
      all: vi.fn(() => []),
    })),
    exec: vi.fn(),
    close: vi.fn(),
  }))
  return { mockPragma, MockDatabase }
})

vi.mock('better-sqlite3', () => ({ default: MockDatabase }))

vi.mock('@/lib/config', () => ({
  config: { dbPath: ':memory:' },
  ensureDirExists: vi.fn(),
}))

vi.mock('@/lib/migrations', () => ({ runMigrations: vi.fn() }))
vi.mock('@/lib/event-bus', () => ({ eventBus: { broadcast: vi.fn(), on: vi.fn() } }))
vi.mock('@/lib/password', () => ({ hashPassword: vi.fn((p: string) => `hashed:${p}`) }))
vi.mock('@/lib/logger', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }))
vi.mock('@/lib/mentions', () => ({ parseMentions: vi.fn(() => []) }))
vi.mock('@/lib/auto-credentials', () => ({ ensureAutoGeneratedCredentials: vi.fn() }))

describe('SQLite busy_timeout pragma', () => {
  beforeEach(() => {
    vi.resetModules()
    mockPragma.mockClear()
    MockDatabase.mockClear()
  })

  it('sets busy_timeout = 5000 on database initialization', async () => {
    // Fresh module import creates a new db connection
    const { getDatabase } = await import('@/lib/db')
    getDatabase()

    const pragmaCalls = mockPragma.mock.calls.map((c) => c[0] as string)
    expect(pragmaCalls).toContain('busy_timeout = 5000')
  })

  it('sets WAL journal mode on database initialization', async () => {
    const { getDatabase } = await import('@/lib/db')
    getDatabase()

    const pragmaCalls = mockPragma.mock.calls.map((c) => c[0] as string)
    expect(pragmaCalls).toContain('journal_mode = WAL')
  })

  it('skips module-level initialization during build phase', async () => {
    const original = process.env.NEXT_PHASE
    process.env.NEXT_PHASE = 'phase-production-build'
    try {
      // Re-import with build phase set — constructor should not be called at module level
      await import('@/lib/db')
      // The mock may have been called 0 times (no eager init) or once (if getDatabase was called)
      // Key assertion: we don't throw during import in build phase
      expect(true).toBe(true)
    } finally {
      process.env.NEXT_PHASE = original
    }
  })
})