Files
Jarvise-project/backend/test/mock-ollama.js
T
BlackAngelTV 877df963f9 test(backend): cover auth, projects and streaming with a mocked Ollama
Tests run without any external service; the mock streams NDJSON chunks so the
SSE path is exercised end to end.
2026-10-05 15:01:57 +02:00

66 lines
2.1 KiB
JavaScript

import http from 'node:http';
const DEFAULT_PIECES = ['Bon', 'jour', ' ', 'Tony', ', ', 'je ', 'suis ', 'Jarvis', '.'];
/**
* Faux serveur Ollama : répond en NDJSON morceau par morceau quand `stream`
* est vrai, et renvoie une erreur si le modèle vaut "boom".
*/
export async function startMockOllama({ pieces = DEFAULT_PIECES, delay = 2 } = {}) {
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/api/tags') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ models: [{ name: 'mock:1' }] }));
return;
}
if (req.method === 'POST' && req.url === '/api/chat') {
let body = '';
req.on('data', (c) => (body += c));
req.on('end', () => {
const payload = JSON.parse(body || '{}');
if (payload.model === 'boom') {
res.writeHead(500, { 'Content-Type': 'application/json' }).end('{"error":"boom"}');
return;
}
const full = pieces.join('');
if (!payload.stream) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ model: payload.model, message: { role: 'assistant', content: full }, done: true }));
return;
}
res.writeHead(200, { 'Content-Type': 'application/x-ndjson' });
let i = 0;
const timer = setInterval(() => {
if (i < pieces.length) {
res.write(
JSON.stringify({ model: payload.model, message: { role: 'assistant', content: pieces[i] }, done: false }) +
'\n',
);
i++;
} else {
clearInterval(timer);
res.write(JSON.stringify({ model: payload.model, done: true }) + '\n');
res.end();
}
}, delay);
});
return;
}
res.writeHead(404).end();
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
return {
url: `http://127.0.0.1:${port}`,
close: () => new Promise((resolve) => server.close(resolve)),
};
}