import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; import { enrichQueries } from './query-enricher'; import type { QueryContext } from './contextual-analyzer'; vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(async () => undefined) })); function stubGenerate(response: unknown, ok = true) { const fetchMock = vi.fn(async () => ({ ok, status: ok ? 200 : 503, statusText: 'x', json: async () => ({ response }) }) as Response); vi.stubGlobal('fetch', fetchMock); return fetchMock; } function sentPrompt(fetchMock: Mock): string { return JSON.parse((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string).prompt; } const CTX: QueryContext = { originalQuery: 'praias em Garuva', intent: 'list', entities: [{ type: 'location', value: 'Garuva', confidence: 1 }], topics: ['praias'], relationships: [], implicitQuestions: [], temporalContext: { period: '2024' }, geographicContext: { location: 'SC' }, keywords: ['praias'], synonyms: ['litoral'], domain: 'turismo', complexity: 'simple', }; const LLM = { literal: ['praias garuva'], semantic: ['litoral garuva'], related: ['melhor praia garuva'], expanded: ['praia itapoá garuva'], contextual: ['praias garuva 2024'], }; describe('enrichQueries', () => { beforeEach(() => vi.spyOn(console, 'error').mockImplementation(() => {})); it('LLM devolve as 5 categorias: repassa e monta o prompt com o contexto', async () => { const fetchMock = stubGenerate(JSON.stringify(LLM)); expect(await enrichQueries('praias em Garuva', CTX, 'qwen')).toEqual(LLM); const prompt = sentPrompt(fetchMock); expect(prompt).toContain('"praias em Garuva"'); expect(prompt).toContain('- Entidades: location: Garuva'); expect(prompt).toContain('- Contexto Temporal: {"period":"2024"}'); expect(prompt).toContain('- Contexto Geográfico: {"location":"SC"}'); expect(prompt).toContain('- Domínio: turismo'); }); it.each([ ['entities', [], '- Entidades: nenhuma'], ['temporalContext', undefined, '- Contexto Temporal: nenhum'], ['geographicContext', undefined, '- Contexto Geográfico: nenhum'], ['topics', [], '- Tópicos: nenhum'], ['keywords', [], '- Palavras-chave: nenhuma'], ['synonyms', [], '- Sinônimos: nenhum'], ['domain', undefined, '- Domínio: geral'], ])('contexto sem %s: prompt usa o marcador vazio', async (field, value, line) => { const fetchMock = stubGenerate(JSON.stringify(LLM)); await enrichQueries('q', { ...CTX, [field]: value }, 'm'); expect(sentPrompt(fetchMock)).toContain(line); }); it('HTTP não ok: fallback com sinônimo, período e local', async () => { stubGenerate(JSON.stringify(LLM), false); expect(await enrichQueries('praias em Garuva', CTX, 'm')).toEqual({ literal: ['praias em Garuva'], semantic: ['litoral em Garuva'], related: [], expanded: [], contextual: ['praias em Garuva 2024', 'praias em Garuva SC'], }); }); it('sem campo response: JSON vazio falha e cai no fallback', async () => { stubGenerate(undefined); expect((await enrichQueries('q', { ...CTX, synonyms: [], temporalContext: undefined, geographicContext: undefined }, 'm'))).toEqual({ literal: ['q'], semantic: [], related: [], expanded: [], contextual: [], }); }); it('fallback com contexto relativo "recente": acrescenta "recente"', async () => { stubGenerate('não é json'); const r = await enrichQueries('q', { ...CTX, synonyms: [], temporalContext: { relative: 'recente' }, geographicContext: undefined }, 'm'); expect(r.contextual).toEqual(['q recente']); }); it('JSON em bloco ```json com texto em volta: extrai o objeto', async () => { stubGenerate(`Aqui:\n\`\`\`json\n${JSON.stringify(LLM)}\n\`\`\``); expect(await enrichQueries('q', CTX, 'm')).toEqual(LLM); }); it('JSON sem objeto (array): todas as categorias vazias e literal com a original', async () => { stubGenerate('[]'); expect(await enrichQueries('q', CTX, 'm')).toEqual({ literal: ['q'], semantic: [], related: [], expanded: [], contextual: [] }); }); it.each([ ['literal', ['q']], ['semantic', []], ['related', []], ['expanded', []], ['contextual', []], ])('categoria %s ausente: usa o padrão e mantém as outras', async (field, fallback) => { const partial: Record = { ...LLM }; delete partial[field]; stubGenerate(JSON.stringify(partial)); expect(await enrichQueries('q', CTX, 'm')).toEqual({ ...LLM, [field]: fallback }); }); it('literal vazio: garante a query original', async () => { stubGenerate(JSON.stringify({ ...LLM, literal: [] })); expect((await enrichQueries('q', CTX, 'm')).literal).toEqual(['q']); }); it('fetch rejeita (Ollama fora do ar): fallback', async () => { vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('refused'); })); expect((await enrichQueries('q', CTX, 'm')).literal).toEqual(['q']); }); });