test: caminhos-base de lib, hooks e services

This commit is contained in:
evandro committed 2026-11-16 00:26:52 -03:00
1 parent 9d911603f7
commit adc37e1921
18 files changed
+2961 -142

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, renderHook } from '@testing-library/react';
import { useQueryPreprocessor, type PreprocessOptions, type PreprocessedQuery } from './use-query-preprocessor';
import { useSettingsStore } from '@/store/settings-store';
// classify_intent é um comando Tauri (Rust): vira fake.
const invokeMock = vi.hoisted(() => vi.fn());
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
function intent(value: string | Error) {
invokeMock.mockImplementation(async (cmd: string) => {
if (cmd !== 'classify_intent') throw new Error(`comando inesperado: ${cmd}`);
if (value instanceof Error) throw value;
return value;
});
}
async function preprocess(text: string, options?: PreprocessOptions) {
const { result } = renderHook(() => useQueryPreprocessor());
let out: PreprocessedQuery | undefined;
await act(async () => {
out = await result.current.preprocess(text, options);
});
expect(result.current.isProcessing).toBe(false);
return out!;
}
const defaults = useSettingsStore.getState();
beforeEach(() => {
invokeMock.mockReset();
localStorage.clear();
useSettingsStore.setState({
queryPreprocessing: defaults.queryPreprocessing,
webSearch: { ...defaults.webSearch, enabled: true },
});
vi.spyOn(console, 'error').mockImplementation(() => {});
});
describe('preprocess', () => {
it('pergunta factual válida: divide, classifica e decide buscar', async () => {
intent('factual');
const r = await preprocess('O que é Rust? Quem criou a linguagem?');
expect(r.validation.isValid).toBe(true);
expect(r.splitResult.splitCount).toBe(2);
expect(r.questions).toHaveLength(2);
expect(r.intent).toBe('factual');
expect(r.shouldSearch).toBe(true);
expect(invokeMock).toHaveBeenCalledWith('classify_intent', { query: r.normalized });
});
it('texto abaixo do mínimo: inválido, sem perguntas, sem busca e sem classificar', async () => {
intent('factual');
const r = await preprocess('ab');
expect(r.validation.isValid).toBe(false);
expect(r).toMatchObject({ questions: [], intent: 'unknown', shouldSearch: false, splitResult: { splitCount: 0 } });
expect(invokeMock).not.toHaveBeenCalled();
});
it('skipValidation: aceita texto abaixo do mínimo', async () => {
intent('factual');
const r = await preprocess('ab', { skipValidation: true });
expect(r.validation).toEqual({ isValid: true, errors: [], warnings: [], normalizedLength: 2 });
expect(r.shouldSearch).toBe(true);
});
it('settings sem queryPreprocessing: usa mínimo 3 padrão', async () => {
useSettingsStore.setState({ queryPreprocessing: undefined as unknown as typeof defaults.queryPreprocessing });
intent('factual');
expect((await preprocess('ab')).validation.isValid).toBe(false);
expect((await preprocess('abc')).validation.isValid).toBe(true);
});
it('padrões irrelevantes configurados: usa os do usuário', async () => {
useSettingsStore.setState({ queryPreprocessing: { ...defaults.queryPreprocessing, irrelevantPatterns: ['rust'] } });
intent('factual');
expect((await preprocess('rust')).validation.warnings).toHaveLength(1);
expect((await preprocess('teste')).validation.warnings).toHaveLength(0);
});
it('lista de padrões vazia: cai nos padrões padrão da validação', async () => {
useSettingsStore.setState({ queryPreprocessing: { ...defaults.queryPreprocessing, irrelevantPatterns: [] } });
intent('factual');
expect((await preprocess('teste')).validation.warnings).toHaveLength(1);
});
it('skipSplit: mantém o texto original como única pergunta', async () => {
intent('factual');
const text = 'O que é Rust? Quem criou a linguagem?';
const r = await preprocess(text, { skipSplit: true });
expect(r.questions).toEqual([text]);
expect(r.splitResult.splitCount).toBe(1);
});
it('skipIntentClassification: intent unknown sem chamar o backend e ainda busca', async () => {
intent('conversational');
const r = await preprocess('preço do dólar', { skipIntentClassification: true });
expect(r.intent).toBe('unknown');
expect(r.shouldSearch).toBe(true);
expect(invokeMock).not.toHaveBeenCalled();
});
it('classificador falha: intent unknown e segue buscando', async () => {
intent(new Error('modelo de intent ausente'));
const r = await preprocess('preço do dólar');
expect(r.intent).toBe('unknown');
expect(r.shouldSearch).toBe(true);
});
it.each([
['technical', true],
['conversational', false],
['opinion', false],
['calculation', false],
])('intent %s: shouldSearch %s', async (value, expected) => {
intent(value);
expect((await preprocess('pergunta qualquer aqui')).shouldSearch).toBe(expected);
});
it('busca web desligada: não busca mesmo com intent factual', async () => {
useSettingsStore.setState({ webSearch: { ...defaults.webSearch, enabled: false } });
intent('factual');
expect((await preprocess('preço do dólar')).shouldSearch).toBe(false);
});
it('settings corrompido sem irrelevantPatterns: devolve resultado de erro sem lançar', async () => {
const { irrelevantPatterns: _omit, ...rest } = defaults.queryPreprocessing;
useSettingsStore.setState({ queryPreprocessing: rest as typeof defaults.queryPreprocessing });
intent('factual');
const r = await preprocess('preço do dólar');
expect(r.validation).toEqual({ isValid: false, errors: ['Erro ao pré-processar query'], warnings: [], normalizedLength: 0 });
expect(r.shouldSearch).toBe(false);
});
});