Files
dbmole-mcp/test/unit/config/sources.test.ts
T

87 lines
2.8 KiB
TypeScript

import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readConfigFile, readEnvConnections } from '../../../src/config/sources.js'
const valid = { name: 'env-pg', type: 'postgres', host: 'h', user: 'u' }
describe('readEnvConnections', () => {
beforeEach(() => {
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.restoreAllMocks()
})
it('returns empty when unset', () => {
expect(readEnvConnections({})).toEqual([])
})
it('parses a JSON array of connections', () => {
const env = { DBMOLE_CONNECTIONS: JSON.stringify([valid]) }
expect(readEnvConnections(env).map((c) => c.name)).toEqual(['env-pg'])
})
it('ignores invalid JSON with a warning', () => {
expect(readEnvConnections({ DBMOLE_CONNECTIONS: 'nope{' })).toEqual([])
expect(console.error).toHaveBeenCalled()
})
it('ignores non-array JSON with a warning', () => {
expect(readEnvConnections({ DBMOLE_CONNECTIONS: '{}' })).toEqual([])
expect(console.error).toHaveBeenCalled()
})
})
describe('readConfigFile', () => {
let dir: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'dbmole-config-'))
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
rmSync(dir, { recursive: true, force: true })
vi.restoreAllMocks()
})
it('returns empty when path is undefined', () => {
expect(readConfigFile(undefined)).toEqual([])
})
it('warns and returns empty for a missing file', () => {
expect(readConfigFile(join(dir, 'absent.json'))).toEqual([])
expect(console.error).toHaveBeenCalled()
})
it('reads { connections: [...] } shape', () => {
const path = join(dir, 'config.json')
writeFileSync(path, JSON.stringify({ connections: [valid] }))
expect(readConfigFile(path).map((c) => c.name)).toEqual(['env-pg'])
})
it('warns on wrong shape', () => {
const path = join(dir, 'config.json')
writeFileSync(path, JSON.stringify([valid]))
expect(readConfigFile(path)).toEqual([])
expect(console.error).toHaveBeenCalled()
})
it('warns on null config', () => {
const path = join(dir, 'config.json')
writeFileSync(path, 'null')
expect(readConfigFile(path)).toEqual([])
expect(console.error).toHaveBeenCalled()
})
it('warns on primitive config', () => {
const path = join(dir, 'config.json')
writeFileSync(path, '"just a string"')
expect(readConfigFile(path)).toEqual([])
expect(console.error).toHaveBeenCalled()
})
})