287 lines
13 KiB
TypeScript
287 lines
13 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
import { ModelDownloadDialog } from './model-download-dialog';
|
|
|
|
// Comandos Tauri (pull_model, seletor nativo de arquivo, install_gguf_model) e o evento de progresso viram fakes.
|
|
const { invokeMock, listeners } = vi.hoisted(() => ({
|
|
invokeMock: vi.fn(),
|
|
listeners: {} as Record<string, (event: { payload: string }) => void>,
|
|
}));
|
|
vi.mock('@tauri-apps/api/core', () => ({ invoke: invokeMock }));
|
|
vi.mock('@tauri-apps/api/event', () => ({
|
|
listen: vi.fn(async (name: string, cb: (event: { payload: string }) => void) => {
|
|
listeners[name] = cb;
|
|
return () => {};
|
|
}),
|
|
}));
|
|
|
|
const backend = {
|
|
installed: false,
|
|
pull: (): Promise<void> => Promise.withResolvers<void>().promise, // download em andamento
|
|
pickFile: async (): Promise<string | null> => null,
|
|
installGguf: async (_args: unknown): Promise<string> => 'modelo-local',
|
|
};
|
|
|
|
beforeEach(() => {
|
|
backend.installed = false;
|
|
backend.pull = () => Promise.withResolvers<void>().promise;
|
|
backend.pickFile = async () => null;
|
|
backend.installGguf = async () => 'modelo-local';
|
|
invokeMock.mockReset();
|
|
invokeMock.mockImplementation(async (cmd: string, args: unknown) => {
|
|
if (cmd === 'check_if_model_installed') return backend.installed;
|
|
if (cmd === 'pull_model') return backend.pull();
|
|
if (cmd === 'open_gguf_file_dialog') return backend.pickFile();
|
|
if (cmd === 'install_gguf_model') return backend.installGguf(args);
|
|
throw new Error(`comando inesperado: ${cmd}`);
|
|
});
|
|
vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
});
|
|
|
|
async function open(onSuccess: ((name: string) => void) | undefined = vi.fn()) {
|
|
const onOpenChange = vi.fn();
|
|
render(<ModelDownloadDialog open onOpenChange={onOpenChange} onSuccess={onSuccess} />);
|
|
await waitFor(() => expect(listeners['download-progress']).toBeDefined());
|
|
return { onOpenChange, onSuccess };
|
|
}
|
|
|
|
const nameField = () => screen.getByLabelText('Nome do Modelo');
|
|
const progress = (payload: object | string) =>
|
|
act(() => listeners['download-progress']({ payload: typeof payload === 'string' ? payload : JSON.stringify(payload) }));
|
|
|
|
async function startDownload(name = 'llama3.2:1b') {
|
|
fireEvent.change(nameField(), { target: { value: name } });
|
|
fireEvent.click(screen.getByRole('button', { name: 'Baixar' }));
|
|
await screen.findByText('Iniciando download...');
|
|
}
|
|
|
|
describe('ModelDownloadDialog: baixar do Ollama', () => {
|
|
it('nome com caractere inválido: botão Baixar desativado e Enter não baixa', async () => {
|
|
await open();
|
|
fireEvent.change(nameField(), { target: { value: 'llama 3' } });
|
|
fireEvent.keyDown(nameField(), { key: 'Enter' });
|
|
expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', true);
|
|
expect(invokeMock).not.toHaveBeenCalledWith('pull_model', expect.anything());
|
|
});
|
|
|
|
it.each(['/llama', 'llama:', '-llama'])('nome "%s" com /, : ou - na ponta: botão desativado', async (name) => {
|
|
await open();
|
|
fireEvent.change(nameField(), { target: { value: name } });
|
|
expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', true);
|
|
});
|
|
|
|
it('Enter com nome válido: inicia o download do nome aparado', async () => {
|
|
await open();
|
|
fireEvent.change(nameField(), { target: { value: ' huihui_ai/qwen3:1.7b ' } });
|
|
fireEvent.keyDown(nameField(), { key: 'Enter' });
|
|
await waitFor(() => expect(invokeMock).toHaveBeenCalledWith('pull_model', { name: 'huihui_ai/qwen3:1.7b' }));
|
|
});
|
|
|
|
it('modelo já instalado: avisa e "Usar Modelo" notifica e fecha sem baixar', async () => {
|
|
backend.installed = true;
|
|
const { onOpenChange, onSuccess } = await open();
|
|
fireEvent.change(nameField(), { target: { value: 'mistral:latest' } });
|
|
expect(await screen.findByText('✓ Este modelo já está instalado')).toBeTruthy();
|
|
fireEvent.click(screen.getByRole('button', { name: 'Usar Modelo' }));
|
|
expect(onSuccess).toHaveBeenCalledWith('mistral:latest');
|
|
expect(onOpenChange).toHaveBeenCalledWith(false);
|
|
expect(invokeMock).not.toHaveBeenCalledWith('pull_model', expect.anything());
|
|
});
|
|
|
|
it('modelo já instalado e Enter: notifica sem baixar e sem fechar', async () => {
|
|
backend.installed = true;
|
|
const { onOpenChange, onSuccess } = await open();
|
|
fireEvent.change(nameField(), { target: { value: 'mistral:latest' } });
|
|
await screen.findByText('✓ Este modelo já está instalado');
|
|
fireEvent.keyDown(nameField(), { key: 'Enter' });
|
|
expect(onSuccess).toHaveBeenCalledWith('mistral:latest');
|
|
expect(onOpenChange).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('pull_model falha com Error: mostra a mensagem e volta ao botão Baixar', async () => {
|
|
const pending = Promise.withResolvers<void>();
|
|
backend.pull = () => pending.promise;
|
|
await open();
|
|
await startDownload();
|
|
await act(async () => pending.reject(new Error('manifest not found')));
|
|
expect(screen.getByText('manifest not found')).toBeTruthy();
|
|
expect(screen.getByRole('button', { name: 'Baixar' })).toHaveProperty('disabled', false);
|
|
});
|
|
|
|
it('pull_model falha sem mensagem: texto genérico', async () => {
|
|
backend.pull = async () => { throw 'erro do rust'; };
|
|
await open();
|
|
fireEvent.change(nameField(), { target: { value: 'llama3.2:1b' } });
|
|
fireEvent.click(screen.getByRole('button', { name: 'Baixar' }));
|
|
expect(await screen.findByText('Falha no download. Tente novamente.')).toBeTruthy();
|
|
});
|
|
});
|
|
|
|
describe('ModelDownloadDialog: evento download-progress', () => {
|
|
it('fora de um download: evento ignorado', async () => {
|
|
await open();
|
|
progress({ status: 'pulling', percent: 50, raw: '' });
|
|
expect(screen.queryByText('50%')).toBeNull();
|
|
});
|
|
|
|
it.each([
|
|
['pulling', 'Baixando modelo...', '10%'],
|
|
['verifying', 'Verificando...', '90%'],
|
|
['writing', 'Salvando...', '95%'],
|
|
['outro', 'Baixando...', '0%'],
|
|
])('status %s sem percent: "%s" e %s', async (status, text, pct) => {
|
|
await open();
|
|
await startDownload();
|
|
progress({ status, raw: '' });
|
|
expect(screen.getByText(text, { selector: 'span' })).toBeTruthy();
|
|
expect(screen.getByText(pct)).toBeTruthy();
|
|
});
|
|
|
|
it('pulling sem percent depois de 40%: não regride', async () => {
|
|
await open();
|
|
await startDownload();
|
|
progress({ status: 'pulling', percent: 40, raw: '' });
|
|
progress({ status: 'pulling', raw: '' });
|
|
expect(screen.getByText('40%')).toBeTruthy();
|
|
});
|
|
|
|
it('payload que não é JSON: status genérico', async () => {
|
|
await open();
|
|
await startDownload();
|
|
progress('pulling manifest');
|
|
expect(screen.getByText('Baixando...', { selector: 'span' })).toBeTruthy();
|
|
});
|
|
|
|
it('baixado, total e velocidade: mostra os três; só baixado: mostra só ele', async () => {
|
|
await open();
|
|
await startDownload();
|
|
progress({ status: 'pulling', percent: 20, downloaded: '1 GB', total: '4 GB', speed: '9 MB/s', raw: '' });
|
|
expect(screen.getByText('1 GB / 4 GB')).toBeTruthy();
|
|
expect(screen.getByText('9 MB/s')).toBeTruthy();
|
|
progress({ status: 'pulling', percent: 21, downloaded: '1.1 GB', raw: '' });
|
|
expect(screen.getByText('1.1 GB')).toBeTruthy();
|
|
});
|
|
|
|
it.each([
|
|
['percent 100', { status: 'pulling', percent: 100, raw: '' }],
|
|
['status success', { status: 'success', raw: '' }],
|
|
])('%s: após 500 ms notifica o modelo e fecha', async (_n, payload) => {
|
|
const { onOpenChange, onSuccess } = await open();
|
|
await startDownload('qwen:0.5b');
|
|
progress(payload);
|
|
expect(onOpenChange).not.toHaveBeenCalled();
|
|
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
|
|
expect(onSuccess).toHaveBeenCalledWith('qwen:0.5b');
|
|
});
|
|
|
|
it('concluído sem onSuccess: só fecha', async () => {
|
|
const { onOpenChange } = await open(undefined);
|
|
await startDownload();
|
|
progress({ status: 'success', raw: '' });
|
|
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
|
|
});
|
|
});
|
|
|
|
describe('ModelDownloadDialog: fechar e cancelar', () => {
|
|
it('cancelar sem download: fecha', async () => {
|
|
const { onOpenChange } = await open();
|
|
fireEvent.click(screen.getByRole('button', { name: 'Cancelar' }));
|
|
expect(onOpenChange).toHaveBeenCalledWith(false);
|
|
});
|
|
|
|
it.each([
|
|
[true, [[false]]],
|
|
[false, []],
|
|
])('cancelar durante download com confirmação %s', async (confirmed, calls) => {
|
|
vi.stubGlobal('confirm', vi.fn(() => confirmed)); // happy-dom não implementa window.confirm
|
|
const { onOpenChange } = await open();
|
|
await startDownload();
|
|
fireEvent.click(screen.getByRole('button', { name: 'Cancelar' }));
|
|
expect(onOpenChange.mock.calls).toEqual(calls);
|
|
});
|
|
|
|
it.each([
|
|
[true, [[false]]],
|
|
[false, []],
|
|
])('Esc durante download com confirmação %s', async (confirmed, calls) => {
|
|
vi.stubGlobal('confirm', vi.fn(() => confirmed));
|
|
const { onOpenChange } = await open();
|
|
await startDownload();
|
|
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
|
|
expect(onOpenChange.mock.calls).toEqual(calls);
|
|
});
|
|
|
|
it('Esc sem download: fecha sem perguntar', async () => {
|
|
const confirm = vi.fn(() => true);
|
|
vi.stubGlobal('confirm', confirm);
|
|
const { onOpenChange } = await open();
|
|
fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });
|
|
expect(onOpenChange).toHaveBeenCalledWith(false);
|
|
expect(confirm).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('ModelDownloadDialog: instalar GGUF local', () => {
|
|
async function openLocal(onSuccess?: (name: string) => void) {
|
|
const r = await open(onSuccess);
|
|
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Instalar Local' }), { button: 0 });
|
|
await screen.findByRole('button', { name: 'Selecionar arquivo GGUF' });
|
|
return r;
|
|
}
|
|
|
|
it('seletor cancelado: não instala nada', async () => {
|
|
await openLocal();
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
|
|
expect(invokeMock).not.toHaveBeenCalledWith('install_gguf_model', expect.anything());
|
|
expect(screen.queryByText('Erro ao instalar modelo')).toBeNull();
|
|
});
|
|
|
|
it('arquivo .GGUF sem nome informado: usa o nome do arquivo sem extensão e fecha depois', async () => {
|
|
backend.pickFile = async () => 'C:\\modelos\\Phi-3.GGUF';
|
|
const { onOpenChange, onSuccess } = await openLocal(vi.fn());
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
|
|
expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: 'C:\\modelos\\Phi-3.GGUF', modelName: 'Phi-3' });
|
|
await waitFor(() => expect(onSuccess).toHaveBeenCalledWith('modelo-local'));
|
|
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false), { timeout: 2000 });
|
|
});
|
|
|
|
it('nome informado: prevalece sobre o do arquivo; arquivo sem .gguf mantém o nome', async () => {
|
|
backend.pickFile = async () => '/home/u/modelo.bin';
|
|
await openLocal();
|
|
fireEvent.change(screen.getByLabelText('Nome do Modelo (opcional)'), { target: { value: ' meu-modelo ' } });
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
|
|
expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: '/home/u/modelo.bin', modelName: 'meu-modelo' });
|
|
});
|
|
|
|
it('caminho terminado em barra: usa "model" como nome', async () => {
|
|
backend.pickFile = async () => '/home/u/';
|
|
await openLocal();
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
|
|
expect(invokeMock).toHaveBeenCalledWith('install_gguf_model', { filePath: '/home/u/', modelName: 'model' });
|
|
});
|
|
|
|
it('instalação falha com Error: mostra a mensagem e volta ao seletor', async () => {
|
|
backend.pickFile = async () => '/m/a.gguf';
|
|
backend.installGguf = async () => { throw new Error('Ollama recusou o Modelfile'); };
|
|
await openLocal();
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
|
|
expect(await screen.findByText('Ollama recusou o Modelfile')).toBeTruthy();
|
|
expect(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })).toBeTruthy();
|
|
});
|
|
|
|
it('instalação falha sem mensagem: texto genérico', async () => {
|
|
backend.pickFile = async () => '/m/a.gguf';
|
|
backend.installGguf = async () => { throw 'falhou'; };
|
|
await openLocal();
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
|
|
expect(await screen.findByText('Erro ao instalar modelo GGUF')).toBeTruthy();
|
|
});
|
|
|
|
it('seletor nativo falha: avisa que não abriu', async () => {
|
|
backend.pickFile = async () => { throw new Error('sem portal xdg'); };
|
|
await openLocal();
|
|
await act(async () => fireEvent.click(screen.getByRole('button', { name: 'Selecionar arquivo GGUF' })));
|
|
expect(await screen.findByText('Erro ao abrir seletor de arquivo')).toBeTruthy();
|
|
});
|
|
});
|