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,276 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { useChatStorage, type SessionSummary } from './use-chat-storage';
|
||||
import type { Message } from './use-chat';
|
||||
|
||||
// Backend Tauri e Ollama (fetch para localhost:11434) viram fakes: nenhum modelo é chamado.
|
||||
const invokeMock = vi.hoisted(() => vi.fn());
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
||||
|
||||
let storedSessions: SessionSummary[] = [];
|
||||
let saveError: unknown = null;
|
||||
|
||||
function session(id: string, title: string): SessionSummary {
|
||||
return { id, title, emoji: '💬', updated_at: '2026-01-01', preview: '', platform: 'Linux' };
|
||||
}
|
||||
|
||||
function ollama(reply: { ok?: boolean; status?: number; content?: unknown } | Error) {
|
||||
const fetchMock = vi.fn(async () => {
|
||||
if (reply instanceof Error) throw reply;
|
||||
return {
|
||||
ok: reply.ok ?? true,
|
||||
status: reply.status ?? 200,
|
||||
json: async () => (reply.content === undefined ? {} : { message: { content: reply.content } }),
|
||||
};
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
return fetchMock;
|
||||
}
|
||||
|
||||
const saves = () =>
|
||||
invokeMock.mock.calls.filter(([cmd]) => cmd === 'save_chat_session').map(([, args]) => args as {
|
||||
id: string; title: string; messages: Message[]; platform: string; memory_context: string[];
|
||||
});
|
||||
|
||||
async function mount() {
|
||||
const hook = renderHook(() => useChatStorage());
|
||||
await waitFor(() => expect(invokeMock).toHaveBeenCalledWith('load_chat_sessions'));
|
||||
await act(async () => {});
|
||||
return hook;
|
||||
}
|
||||
|
||||
const user = (content: string): Message => ({ role: 'user', content });
|
||||
const bot = (content: string, metadata?: unknown): Message => ({ role: 'assistant', content, metadata });
|
||||
|
||||
beforeEach(() => {
|
||||
storedSessions = [];
|
||||
saveError = null;
|
||||
invokeMock.mockReset();
|
||||
invokeMock.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === 'load_chat_sessions') return storedSessions;
|
||||
if (cmd === 'save_chat_session') {
|
||||
if (saveError) throw saveError;
|
||||
return undefined;
|
||||
}
|
||||
throw new Error(`comando inesperado: ${cmd}`);
|
||||
});
|
||||
vi.spyOn(navigator, 'platform', 'get').mockReturnValue('Linux x86_64');
|
||||
for (const level of ['log', 'warn', 'error'] as const) vi.spyOn(console, level).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
describe('generateTitleFromUserMessage', () => {
|
||||
it('modelo responde título: devolve o título limpo', async () => {
|
||||
ollama({ content: ' Receita de bolo ' });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('como faço bolo?')).toBe('Receita de bolo');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['404 (modelo ausente)', 404],
|
||||
['500 (erro do servidor)', 500],
|
||||
['400 (outro erro)', 400],
|
||||
])('HTTP %s: usa a mensagem do usuário', async (_n, status) => {
|
||||
ollama({ ok: false, status });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage(' pergunta curta ')).toBe('pergunta curta');
|
||||
});
|
||||
|
||||
it('fetch rejeita (Ollama fora do ar): usa a mensagem do usuário', async () => {
|
||||
ollama(new TypeError('Failed to fetch'));
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('oi')).toBe('oi');
|
||||
});
|
||||
|
||||
it('resposta sem message.content: usa a mensagem do usuário', async () => {
|
||||
ollama({});
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('oi')).toBe('oi');
|
||||
});
|
||||
|
||||
it('título entre aspas: remove as aspas', async () => {
|
||||
ollama({ content: `"'Viagem a Roma'"` });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('x')).toBe('Viagem a Roma');
|
||||
});
|
||||
|
||||
it('título só com pontuação: usa a mensagem do usuário', async () => {
|
||||
ollama({ content: '"..."' });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('pergunta')).toBe('pergunta');
|
||||
});
|
||||
|
||||
it('título só com bloco <metadata>: usa a mensagem do usuário', async () => {
|
||||
ollama({ content: '<metadata>{"a":1}</metadata>' });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('pergunta')).toBe('pergunta');
|
||||
});
|
||||
|
||||
it('título com mais de 60 caracteres: corta em 60 e põe reticências', async () => {
|
||||
ollama({ content: 'x'.repeat(80) });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('p')).toBe('x'.repeat(60) + '...');
|
||||
});
|
||||
|
||||
it('fallback com mensagem acima de 50 caracteres: corta em 50 e põe reticências', async () => {
|
||||
ollama({ ok: false, status: 404 });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage('y'.repeat(70))).toBe('y'.repeat(50) + '...');
|
||||
});
|
||||
|
||||
it('fallback com mensagem em branco: "Nova Conversa"', async () => {
|
||||
ollama({ ok: false, status: 404 });
|
||||
const { result } = await mount();
|
||||
expect(await result.current.generateTitleFromUserMessage(' ')).toBe('Nova Conversa');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saveSession', () => {
|
||||
it('sem mensagens: não salva', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', []));
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
|
||||
it('sessão existente com título: salva com o título atual e as keywords de string sem repetir', async () => {
|
||||
storedSessions = [session('s1', 'Título salvo')];
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [
|
||||
user('q'),
|
||||
bot('a', { keywords: ['rust', 'tauri', 7] }),
|
||||
bot('b', { keywords: ['rust'] }),
|
||||
bot('c', { keywords: 'não é lista' }),
|
||||
user('d'),
|
||||
]));
|
||||
expect(saves()).toEqual([expect.objectContaining({ id: 's1', title: 'Título salvo', platform: 'Linux x86_64', memory_context: ['rust', 'tauri'] })]);
|
||||
});
|
||||
|
||||
it('sessão existente e currentTitle informado: currentTitle prevalece', async () => {
|
||||
storedSessions = [session('s1', 'Antigo')];
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')], 'Renomeado'));
|
||||
expect(saves()[0].title).toBe('Renomeado');
|
||||
});
|
||||
|
||||
it('sessão existente: falha ao salvar não propaga nem recarrega a lista', async () => {
|
||||
storedSessions = [session('s1', 'Antigo')];
|
||||
saveError = new Error('disco cheio');
|
||||
const { result } = await mount();
|
||||
const loadsBefore = invokeMock.mock.calls.filter(([c]) => c === 'load_chat_sessions').length;
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(invokeMock.mock.calls.filter(([c]) => c === 'load_chat_sessions')).toHaveLength(loadsBefore);
|
||||
});
|
||||
|
||||
it('platform vazio: usa o primeiro token do userAgent', async () => {
|
||||
storedSessions = [session('s1', 'Antigo')];
|
||||
vi.spyOn(navigator, 'platform', 'get').mockReturnValue('');
|
||||
vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Mozilla/5.0 (X11)');
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(saves()[0].platform).toBe('Mozilla/5.0');
|
||||
});
|
||||
|
||||
it('sessão nova com só a mensagem do usuário: espera a resposta e não salva', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
|
||||
it('sessão existente com "Nova Conversa" e 1 mensagem: tratada como nova, não salva', async () => {
|
||||
storedSessions = [session('s1', 'Nova Conversa')];
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q')]));
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
|
||||
it('sessão nova com currentTitle: salva já com ele, sem chamar o modelo', async () => {
|
||||
const fetchMock = ollama({ content: 'não usar' });
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a')], 'Dado'));
|
||||
expect(saves()[0].title).toBe('Dado');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('sessão nova com metadata.title: usa o título aparado', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { title: ' Do modelo ', summary: 'resumo' })]));
|
||||
expect(saves()[0].title).toBe('Do modelo');
|
||||
});
|
||||
|
||||
it('sessão nova com só metadata.summary: usa o resumo', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { summary: ' Resumo ' })]));
|
||||
expect(saves()[0].title).toBe('Resumo');
|
||||
});
|
||||
|
||||
it('metadata.title em branco: passa para a próxima resposta do assistente', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { title: ' ' }), bot('b', { summary: 'Segundo' })]));
|
||||
expect(saves()[0].title).toBe('Segundo');
|
||||
});
|
||||
|
||||
it('metadata.summary em branco: segue para a próxima resposta', async () => {
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { summary: ' ' }), bot('b', { title: 'Terceiro' })]));
|
||||
expect(saves()[0].title).toBe('Terceiro');
|
||||
});
|
||||
|
||||
it('sessão nova com metadata.title: falha ao salvar não propaga', async () => {
|
||||
saveError = new Error('disco cheio');
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a', { title: 'T' })]));
|
||||
expect(saves()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('sem título em metadata: gera com o modelo usando até 4 mensagens sem metadata e salva', async () => {
|
||||
const fetchMock = ollama({ content: 'Título gerado' });
|
||||
const { result } = await mount();
|
||||
const msgs = [user('q1'), bot('r1 <metadata>{"x":1}</metadata>'), user('q2'), bot('r2'), user('q3')];
|
||||
await act(() => result.current.saveSession('s1', msgs));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
expect(saves()[0].title).toBe('Título gerado');
|
||||
const sent = JSON.parse((fetchMock.mock.calls[0] as unknown as [string, { body: string }])[1].body).messages;
|
||||
expect(sent.slice(1).map((m: Message) => m.content)).toEqual(['q1', 'r1', 'q2', 'r2']);
|
||||
expect(result.current.isGeneratingTitle).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['HTTP 404', { ok: false, status: 404 }],
|
||||
['HTTP 400', { ok: false, status: 400 }],
|
||||
['resposta vazia', { content: '' }],
|
||||
['título só pontuação', { content: '"!!"' }],
|
||||
['erro de rede', new Error('Failed to fetch')],
|
||||
])('geração falha (%s): salva com o início da primeira pergunta', async (_n, reply) => {
|
||||
ollama(reply);
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [bot('olá'), user(`${'p'.repeat(60)} <metadata>{}</metadata>`)]));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
expect(saves()[0].title).toBe('p'.repeat(50) + '...');
|
||||
expect(result.current.isGeneratingTitle).toBe(false);
|
||||
});
|
||||
|
||||
it('geração falha e não há mensagem do usuário: "Nova Conversa"', async () => {
|
||||
ollama({ ok: false, status: 404 });
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [bot('a'), bot('b')]));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
expect(saves()[0].title).toBe('Nova Conversa');
|
||||
});
|
||||
|
||||
it('título gerado mas falha ao salvar: libera isGeneratingTitle', async () => {
|
||||
ollama({ content: 'Ok' });
|
||||
saveError = new Error('disco cheio');
|
||||
const { result } = await mount();
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a')]));
|
||||
await waitFor(() => expect(saves()).toHaveLength(1));
|
||||
await waitFor(() => expect(result.current.isGeneratingTitle).toBe(false));
|
||||
});
|
||||
|
||||
it('geração de título já em andamento: não dispara outra', async () => {
|
||||
const fetchMock = ollama({ content: 'x' });
|
||||
const { result } = await mount();
|
||||
act(() => result.current.setIsGeneratingTitle(true));
|
||||
await act(() => result.current.saveSession('s1', [user('q'), bot('a')]));
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(saves()).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user