test: caminhos-base de lib, hooks e services
This commit is contained in:
1 parent
9d911603f7
commit
adc37e1921
18 files changed
+2961
-142
No files matched your search
@@ -0,0 +1,164 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { analyzeQueryContext } from './contextual-analyzer';
|
||||
|
||||
// Logs do chatLog vão para o Tauri; aqui viram no-op.
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: vi.fn(async () => undefined) }));
|
||||
|
||||
// Fake do /api/generate do Ollama (stream: false).
|
||||
function stubGenerate(response: unknown, ok = true) {
|
||||
const fetchMock = vi.fn(async () => ({ ok, status: ok ? 200 : 500, statusText: 'x', json: async () => ({ response }) }) as Response);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
const FULL = {
|
||||
intent: 'comparison',
|
||||
entities: [{ type: 'product', value: 'Rust', confidence: 0.9 }],
|
||||
topics: ['linguagens'],
|
||||
relationships: [{ from: 'Rust', to: 'Go', relation: 'vs', confidence: 0.8 }],
|
||||
implicitQuestions: ['qual é mais rápida?'],
|
||||
temporalContext: { period: '2024' },
|
||||
geographicContext: { location: 'Brasil' },
|
||||
keywords: ['rust', 'go'],
|
||||
synonyms: ['linguagem'],
|
||||
domain: 'tecnologia',
|
||||
complexity: 'complex',
|
||||
};
|
||||
|
||||
describe('analyzeQueryContext', () => {
|
||||
beforeEach(() => vi.spyOn(console, 'error').mockImplementation(() => {}));
|
||||
|
||||
it('LLM devolve JSON completo: usa todos os campos', async () => {
|
||||
const fetchMock = stubGenerate(JSON.stringify(FULL));
|
||||
const ctx = await analyzeQueryContext('rust vs go', 'qwen');
|
||||
expect(ctx).toEqual({ originalQuery: 'rust vs go', ...FULL });
|
||||
const body = JSON.parse((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string);
|
||||
expect(body).toMatchObject({ model: 'qwen', stream: false });
|
||||
expect(body.prompt).toContain('"rust vs go"');
|
||||
});
|
||||
|
||||
it('query vazia: contexto vazio sem chamar o modelo', async () => {
|
||||
const fetchMock = stubGenerate('{}');
|
||||
const ctx = await analyzeQueryContext('', 'm');
|
||||
expect(ctx.intent).toBe('unknown');
|
||||
expect(ctx.complexity).toBe('simple');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('query só com espaços: contexto vazio sem chamar o modelo', async () => {
|
||||
const fetchMock = stubGenerate('{}');
|
||||
expect((await analyzeQueryContext(' ', 'm')).keywords).toEqual([]);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('HTTP não ok: cai no fallback heurístico', async () => {
|
||||
stubGenerate(JSON.stringify(FULL), false);
|
||||
const ctx = await analyzeQueryContext('como instalar rust', 'm');
|
||||
expect(ctx.intent).toBe('how-to');
|
||||
expect(ctx.entities).toEqual([]);
|
||||
});
|
||||
|
||||
it('resposta sem campo response: JSON vazio falha e cai no fallback', async () => {
|
||||
stubGenerate(undefined);
|
||||
expect((await analyzeQueryContext('lista de livros', 'm')).intent).toBe('list');
|
||||
});
|
||||
|
||||
it('JSON dentro de bloco ```json com texto em volta: extrai o objeto', async () => {
|
||||
stubGenerate('Claro!\n```json\n{"intent":"definition"}\n```');
|
||||
expect((await analyzeQueryContext('x', 'm')).intent).toBe('definition');
|
||||
});
|
||||
|
||||
it('JSON sem objeto (array): aceita e preenche os padrões', async () => {
|
||||
stubGenerate('[]');
|
||||
expect(await analyzeQueryContext('x', 'm')).toEqual({
|
||||
originalQuery: 'x',
|
||||
intent: 'unknown',
|
||||
entities: [],
|
||||
topics: [],
|
||||
relationships: [],
|
||||
implicitQuestions: [],
|
||||
temporalContext: undefined,
|
||||
geographicContext: undefined,
|
||||
keywords: [],
|
||||
synonyms: [],
|
||||
domain: undefined,
|
||||
complexity: 'moderate',
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['intent', 'unknown'],
|
||||
['entities', []],
|
||||
['topics', []],
|
||||
['relationships', []],
|
||||
['implicitQuestions', []],
|
||||
['keywords', []],
|
||||
['synonyms', []],
|
||||
['complexity', 'moderate'],
|
||||
])('campo %s ausente: usa o padrão e mantém os demais', async (field, fallback) => {
|
||||
const partial: Record<string, unknown> = { ...FULL };
|
||||
delete partial[field];
|
||||
stubGenerate(JSON.stringify(partial));
|
||||
const ctx = await analyzeQueryContext('q', 'm');
|
||||
expect(ctx).toEqual({ originalQuery: 'q', ...FULL, [field]: fallback });
|
||||
});
|
||||
|
||||
it('JSON inválido: cai no fallback heurístico', async () => {
|
||||
stubGenerate('{intent: oops');
|
||||
expect((await analyzeQueryContext('por que o céu é azul', 'm')).intent).toBe('causal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createFallbackContext (via Ollama fora do ar)', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('connection refused'); }));
|
||||
});
|
||||
|
||||
it('query factual sem marcadores: intent factual, sem contexto temporal', async () => {
|
||||
const ctx = await analyzeQueryContext('preço do petróleo hoje', 'm');
|
||||
expect(ctx).toMatchObject({ intent: 'factual', keywords: ['preço', 'petróleo', 'hoje'], topics: ['preço', 'petróleo', 'hoje'], complexity: 'moderate' });
|
||||
expect(ctx.temporalContext).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['como', 'como fazer pão', 'how-to'],
|
||||
['tutorial', 'tutorial de git', 'how-to'],
|
||||
['o que é', 'o que é kubernetes', 'definition'],
|
||||
['definição', 'definição de entropia', 'definition'],
|
||||
['quais', 'quais linguagens usar', 'list'],
|
||||
['lista', 'lista de capitais', 'list'],
|
||||
['comparar', 'comparar planos', 'comparison'],
|
||||
['vs', 'react vs vue', 'comparison'],
|
||||
['por que', 'por que chove', 'causal'],
|
||||
['causa', 'causa da inflação', 'causal'],
|
||||
])('marcador "%s": intent correspondente', async (_m, query, intent) => {
|
||||
expect((await analyzeQueryContext(query, 'm')).intent).toBe(intent);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['último', 'último lançamento da apple'],
|
||||
['recente', 'notícia recente'],
|
||||
['atual', 'cotação atual do dólar'],
|
||||
])('termo relativo "%s": temporal recente', async (_t, query) => {
|
||||
expect((await analyzeQueryContext(query, 'm')).temporalContext).toEqual({ relative: 'recente' });
|
||||
});
|
||||
|
||||
it.each([['2024'], ['2023']])('ano %s isolado: vira período', async (year) => {
|
||||
expect((await analyzeQueryContext(`copa ${year}`, 'm')).temporalContext).toEqual({ period: year });
|
||||
});
|
||||
|
||||
it('ano grudado em outra palavra: sem período', async () => {
|
||||
expect((await analyzeQueryContext('versao2024 notas', 'm')).temporalContext).toBeUndefined();
|
||||
});
|
||||
|
||||
it('mais de 5 keywords: complex', async () => {
|
||||
expect((await analyzeQueryContext('alfa beta gama delta epsilon zeta', 'm')).complexity).toBe('complex');
|
||||
});
|
||||
|
||||
it('até 2 keywords: simple, stopwords e palavras curtas fora', async () => {
|
||||
const ctx = await analyzeQueryContext('o mar de lua', 'm');
|
||||
expect(ctx.keywords).toEqual(['mar', 'lua']);
|
||||
expect(ctx.complexity).toBe('simple');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user