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,166 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { SearchConfig, SearchResultMetadata } from './webSearch';
|
||||
|
||||
// O backend Rust (Tauri) vira um fake: nenhum motor de busca real é chamado.
|
||||
const invokeMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
||||
|
||||
const META: SearchResultMetadata = { title: 'T', url: 'https://ex.com/a', snippet: 's' };
|
||||
const ENGINES = ['google', 'bing', 'yahoo', 'duckduckgo', 'startpage'];
|
||||
|
||||
// O serviço é um singleton com circuit breaker e cache de falhas: módulo novo por teste.
|
||||
async function load() {
|
||||
vi.resetModules();
|
||||
const { webSearchService } = await import('./webSearch');
|
||||
const { useSettingsStore } = await import('@/store/settings-store');
|
||||
const { EngineCircuitBreaker } = await import('./engine-circuit-breaker');
|
||||
const { FailureCache } = await import('./failure-cache');
|
||||
return { svc: webSearchService, store: useSettingsStore, EngineCircuitBreaker, FailureCache };
|
||||
}
|
||||
|
||||
function backend(metadata: () => Promise<unknown>) {
|
||||
invokeMock.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'search_web_metadata') return metadata();
|
||||
if (cmd === 'scrape_urls') return [];
|
||||
throw new Error(`comando inesperado: ${cmd}`);
|
||||
});
|
||||
}
|
||||
|
||||
const metadataCalls = () => invokeMock.mock.calls.filter(([cmd]) => cmd === 'search_web_metadata');
|
||||
|
||||
describe('executeMetadataSearch (via smartSearchRag)', () => {
|
||||
beforeEach(() => {
|
||||
invokeMock.mockReset();
|
||||
localStorage.clear(); // o persist do zustand reidrataria settings de outro teste
|
||||
for (const level of ['log', 'warn', 'error'] as const) vi.spyOn(console, level).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
it('backend devolve metadados: repassa a query aparada, limite e ordem de motores', async () => {
|
||||
const { svc } = await load();
|
||||
backend(async () => [META]);
|
||||
const r = await svc.smartSearchRag(' rust ', 1);
|
||||
expect(r.metadata).toEqual([META]);
|
||||
expect(metadataCalls()[0][1]).toEqual({ query: 'rust', limit: 5, search_config: undefined, engineOrder: ENGINES });
|
||||
});
|
||||
|
||||
it('query com falha recente e resultados parciais: devolve os parciais sem chamar o backend', async () => {
|
||||
const { svc, FailureCache } = await load();
|
||||
vi.spyOn(FailureCache.prototype, 'get').mockReturnValue({ query: 'q', timestamp: Date.now(), error: 'x', partialResults: [META], attempts: 1 });
|
||||
backend(async () => []);
|
||||
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([META]);
|
||||
expect(metadataCalls()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('query com falha recente sem parciais: vazio sem chamar o backend', async () => {
|
||||
const { svc, FailureCache } = await load();
|
||||
vi.spyOn(FailureCache.prototype, 'get').mockReturnValue({ query: 'q', timestamp: Date.now(), error: 'x', partialResults: [], attempts: 1 });
|
||||
backend(async () => [META]);
|
||||
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||
expect(metadataCalls()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('settings sem engineOrder: usa a ordem padrão de motores', async () => {
|
||||
const { svc, store } = await load();
|
||||
store.setState({ webSearch: { ...store.getState().webSearch, engineOrder: undefined as unknown as string[] } });
|
||||
backend(async () => [META]);
|
||||
await svc.smartSearchRag('q', 1);
|
||||
expect(metadataCalls()[0][1]).toMatchObject({ engineOrder: ENGINES });
|
||||
});
|
||||
|
||||
it('todos os motores com circuit breaker aberto: tenta todos mesmo assim', async () => {
|
||||
const { svc, EngineCircuitBreaker } = await load();
|
||||
vi.spyOn(EngineCircuitBreaker.prototype, 'getAvailableEngines').mockReturnValue([]);
|
||||
backend(async () => [META]);
|
||||
await svc.smartSearchRag('q', 1);
|
||||
expect(metadataCalls()[0][1]).toMatchObject({ engineOrder: ENGINES });
|
||||
});
|
||||
|
||||
it('motor com circuit breaker aberto: sai da lista enviada ao backend', async () => {
|
||||
const { svc, EngineCircuitBreaker } = await load();
|
||||
vi.spyOn(EngineCircuitBreaker.prototype, 'getAvailableEngines').mockReturnValue(['bing']);
|
||||
backend(async () => [META]);
|
||||
await svc.smartSearchRag('q', 1);
|
||||
expect(metadataCalls()[0][1]).toMatchObject({ engineOrder: ['bing'] });
|
||||
});
|
||||
|
||||
it('com SearchConfig: converte para o formato snake_case do Rust', async () => {
|
||||
const { svc } = await load();
|
||||
backend(async () => [META]);
|
||||
const config: SearchConfig = {
|
||||
maxConcurrentTabs: 2,
|
||||
totalSourcesLimit: 7,
|
||||
categories: [{ id: 'c', name: 'Cat', baseSites: ['a.com'], enabled: true }],
|
||||
userCustomSites: ['b.com'],
|
||||
excludedDomains: ['x.com'],
|
||||
};
|
||||
await svc.smartSearchRag('q', 1, config);
|
||||
expect(metadataCalls()[0][1]).toMatchObject({
|
||||
search_config: {
|
||||
max_concurrent_tabs: 2,
|
||||
total_sources_limit: 7,
|
||||
categories: [{ id: 'c', name: 'Cat', base_sites: ['a.com'], enabled: true }],
|
||||
user_custom_sites: ['b.com'],
|
||||
excluded_domains: ['x.com'],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('sucesso: registra acerto só para o primeiro motor', async () => {
|
||||
const { svc, EngineCircuitBreaker } = await load();
|
||||
const record = vi.spyOn(EngineCircuitBreaker.prototype, 'recordAttempt');
|
||||
backend(async () => [META]);
|
||||
await svc.smartSearchRag('q', 1);
|
||||
expect(record).toHaveBeenCalledTimes(1);
|
||||
expect(record).toHaveBeenCalledWith('google', true, expect.any(Number));
|
||||
});
|
||||
|
||||
it('sucesso com lista de motores vazia: não registra no circuit breaker', async () => {
|
||||
const { svc, store, EngineCircuitBreaker } = await load();
|
||||
store.setState({ webSearch: { ...store.getState().webSearch, engineOrder: [] } });
|
||||
const record = vi.spyOn(EngineCircuitBreaker.prototype, 'recordAttempt');
|
||||
backend(async () => [META]);
|
||||
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([META]);
|
||||
expect(record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('erro não recuperável: uma tentativa, falha em todos os motores, vazio e query bloqueada', async () => {
|
||||
const { svc, EngineCircuitBreaker } = await load();
|
||||
const record = vi.spyOn(EngineCircuitBreaker.prototype, 'recordAttempt');
|
||||
backend(async () => { throw new Error('permission denied'); });
|
||||
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||
expect(metadataCalls()).toHaveLength(1);
|
||||
expect(record.mock.calls.map(([engine, ok]) => [engine, ok])).toEqual(ENGINES.map((e) => [e, false]));
|
||||
await svc.smartSearchRag('q', 1);
|
||||
expect(metadataCalls()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('erro recuperável: 3 tentativas com backoff, vazio e query bloqueada', async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { svc } = await load();
|
||||
backend(async () => { throw new Error('network unreachable'); });
|
||||
const pending = svc.smartSearchRag('q', 1);
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
expect((await pending).metadata).toEqual([]);
|
||||
expect(metadataCalls()).toHaveLength(3);
|
||||
await svc.smartSearchRag('q', 1);
|
||||
expect(metadataCalls()).toHaveLength(3);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejeição que não é Error: tratada como falha e devolve vazio', async () => {
|
||||
const { svc } = await load();
|
||||
backend(() => Promise.reject('boom'));
|
||||
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||
});
|
||||
|
||||
it('backend devolve lista vazia: vazio e sem bloquear a query', async () => {
|
||||
const { svc } = await load();
|
||||
backend(async () => []);
|
||||
expect((await svc.smartSearchRag('q', 1)).metadata).toEqual([]);
|
||||
await svc.smartSearchRag('q', 1);
|
||||
expect(metadataCalls()).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user