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.
This commit is contained in:
BlackAngelTV committed 2026-10-05 15:01:57 +02:00
1 parent 32dd462be5
commit 877df963f9
6 files changed
+622

No files matched your search

+126
View File
@@ -0,0 +1,126 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { api, registerUser, startServer } from './helpers.js';
describe('authentication', () => {
let srv;
before(async () => {
srv = await startServer();
});
after(async () => {
await srv.close();
});
it('registers a user and returns a token', async () => {
const res = await api(srv.base, 'POST', '/api/auth/register', {
body: { email: 'register@x.io', password: 'motdepasse123', name: 'Tony' },
});
assert.equal(res.status, 201);
assert.ok(res.json.token, 'expected a token');
assert.deepEqual(
{ email: res.json.user.email, name: res.json.user.name },
{ email: 'register@x.io', name: 'Tony' },
);
assert.equal(res.json.user.password_hash, undefined, 'the hash must never leak');
});
it('rejects an already used email', async () => {
await api(srv.base, 'POST', '/api/auth/register', {
body: { email: 'duplicate@x.io', password: 'motdepasse123' },
});
const res = await api(srv.base, 'POST', '/api/auth/register', {
body: { email: 'duplicate@x.io', password: 'motdepasse123' },
});
assert.equal(res.status, 409);
});
it('validates input (short password, invalid email)', async () => {
const short = await api(srv.base, 'POST', '/api/auth/register', {
body: { email: 'short@x.io', password: '123' },
});
assert.equal(short.status, 400);
const bad = await api(srv.base, 'POST', '/api/auth/register', {
body: { email: 'not-an-email', password: 'motdepasse123' },
});
assert.equal(bad.status, 400);
});
it('logs a valid user in', async () => {
await api(srv.base, 'POST', '/api/auth/register', {
body: { email: 'login@x.io', password: 'motdepasse123' },
});
const res = await api(srv.base, 'POST', '/api/auth/login', {
body: { email: 'login@x.io', password: 'motdepasse123' },
});
assert.equal(res.status, 200);
assert.ok(res.json.token);
});
it('rejects a wrong password or email', async () => {
const wrongPass = await api(srv.base, 'POST', '/api/auth/login', {
body: { email: 'login@x.io', password: 'wrong-password' },
});
assert.equal(wrongPass.status, 401);
const unknown = await api(srv.base, 'POST', '/api/auth/login', {
body: { email: 'unknown@x.io', password: 'motdepasse123' },
});
assert.equal(unknown.status, 401);
assert.equal(unknown.json.error, 'Incorrect email or password.');
});
it('protects /api/auth/me', async () => {
const { token } = await registerUser(srv.base, 'me@x.io');
const ok = await api(srv.base, 'GET', '/api/auth/me', { token });
assert.equal(ok.status, 200);
assert.equal(ok.json.user.email, 'me@x.io');
assert.equal((await api(srv.base, 'GET', '/api/auth/me')).status, 401);
assert.equal((await api(srv.base, 'GET', '/api/auth/me', { token: 'garbage' })).status, 401);
});
it('updates the profile', async () => {
const { token } = await registerUser(srv.base, 'profile@x.io');
const res = await api(srv.base, 'PATCH', '/api/auth/me', { token, body: { name: 'Jarvis' } });
assert.equal(res.status, 200);
assert.equal(res.json.user.name, 'Jarvis');
});
it('changes the password and invalidates the old one', async () => {
const email = 'password@x.io';
const { token } = await registerUser(srv.base, email);
const wrong = await api(srv.base, 'POST', '/api/auth/password', {
token,
body: { currentPassword: 'wrong', newPassword: 'newpassword123' },
});
assert.equal(wrong.status, 401);
const ok = await api(srv.base, 'POST', '/api/auth/password', {
token,
body: { currentPassword: 'motdepasse123', newPassword: 'newpassword123' },
});
assert.equal(ok.status, 204);
const newLogin = await api(srv.base, 'POST', '/api/auth/login', {
body: { email, password: 'newpassword123' },
});
assert.equal(newLogin.status, 200);
const oldLogin = await api(srv.base, 'POST', '/api/auth/login', {
body: { email, password: 'motdepasse123' },
});
assert.equal(oldLogin.status, 401);
});
it('logs out (204)', async () => {
const { token } = await registerUser(srv.base, 'logout@x.io');
assert.equal((await api(srv.base, 'POST', '/api/auth/logout', { token })).status, 204);
});
});
+31
View File
@@ -0,0 +1,31 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { api, startServer } from './helpers.js';
describe('health', () => {
let srv;
before(async () => {
srv = await startServer();
});
after(async () => {
await srv.close();
});
it('reports ok with the database and Ollama status', async () => {
const res = await api(srv.base, 'GET', '/health');
assert.equal(res.status, 200);
assert.equal(res.json.status, 'ok');
assert.equal(res.json.database, 'ok');
assert.equal(res.json.ollama.reachable, true);
assert.ok(res.json.ollama.models.includes('mock:1'));
});
it('returns a JSON 404 for an unknown route', async () => {
const res = await api(srv.base, 'GET', '/api/unknown');
assert.equal(res.status, 404);
assert.ok(res.json.error);
});
});
+107
View File
@@ -0,0 +1,107 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { buildApp } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { createDatabase } from '../src/db/index.js';
import { createOllama } from '../src/services/ollama.js';
import { startMockOllama } from './mock-ollama.js';
/** Starts an isolated instance (in-memory database + mock Ollama) on a free port. */
export async function startServer(options = {}) {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jarvise-test-'));
const mock = await startMockOllama(options);
const config = loadConfig({
env: 'test',
jwtSecret: 'test-secret',
dbPath: ':memory:',
ollamaUrl: mock.url,
ollamaModel: 'mock:1',
});
const db = createDatabase(config.dbPath);
const ollama = createOllama(config);
const app = await buildApp({ config, db, ollama });
await app.listen({ port: 0, host: '127.0.0.1' });
const { port } = app.server.address();
return {
app,
db,
mock,
base: `http://127.0.0.1:${port}`,
async close() {
await app.close();
await mock.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
},
};
}
/** Simple JSON request; only sets Content-Type when there is a body. */
export async function api(base, method, apiPath, { token, body, headers = {} } = {}) {
const res = await fetch(base + apiPath, {
method,
headers: {
...(body ? { 'Content-Type': 'application/json' } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
...headers,
},
body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
json = text;
}
return { status: res.status, json, headers: res.headers };
}
/** Creates a user and returns its token. */
export async function registerUser(base, email = `u${Date.now()}${Math.random()}@x.io`) {
const res = await api(base, 'POST', '/api/auth/register', {
body: { email, password: 'motdepasse123', name: 'Test' },
});
if (res.status !== 201) throw new Error(`register failed: ${JSON.stringify(res.json)}`);
return { token: res.json.token, user: res.json.user, email };
}
/**
* Consumes an SSE stream and returns the events as `{ event, data }` objects.
*/
export async function readSse(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
const events = [];
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let sep;
while ((sep = buffer.indexOf('\n\n')) !== -1) {
const block = buffer.slice(0, sep);
buffer = buffer.slice(sep + 2);
if (!block || block.startsWith(':')) continue;
let event = 'message';
let data = '';
for (const line of block.split('\n')) {
if (line.startsWith('event: ')) event = line.slice(7).trim();
else if (line.startsWith('data: ')) data += line.slice(6);
}
events.push({ event, data: data ? JSON.parse(data) : null });
}
}
return events;
}
+65
View File
@@ -0,0 +1,65 @@
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)),
};
}
+180
View File
@@ -0,0 +1,180 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { api, registerUser, startServer } from './helpers.js';
describe('projects and context', () => {
let srv;
let alice;
let bob;
before(async () => {
srv = await startServer();
alice = await registerUser(srv.base, 'alice@x.io');
bob = await registerUser(srv.base, 'bob@x.io');
});
after(async () => {
await srv.close();
});
async function newProject(name = 'Home') {
const res = await api(srv.base, 'POST', '/api/projects', {
token: alice.token,
body: { name, description: 'Home automation' },
});
assert.equal(res.status, 201);
return res.json.project;
}
it('creates and lists its projects', async () => {
const p = await newProject('Created');
assert.equal(p.name, 'Created');
assert.equal(p.messageCount, 0);
const list = await api(srv.base, 'GET', '/api/projects', { token: alice.token });
assert.equal(list.status, 200);
assert.ok(list.json.projects.some((x) => x.id === p.id));
});
it('requires a token', async () => {
assert.equal((await api(srv.base, 'GET', '/api/projects')).status, 401);
assert.equal((await api(srv.base, 'POST', '/api/projects', { body: { name: 'x' } })).status, 401);
});
it('validates the project name', async () => {
assert.equal(
(await api(srv.base, 'POST', '/api/projects', { token: alice.token, body: { name: '' } })).status,
400,
);
});
it('isolates projects between users', async () => {
const p = await newProject('Private');
// Bob does not see Alice's project…
const bobList = await api(srv.base, 'GET', '/api/projects', { token: bob.token });
assert.equal(bobList.json.projects.some((x) => x.id === p.id), false);
// …and gets a 404 on every operation.
assert.equal((await api(srv.base, 'GET', `/api/projects/${p.id}`, { token: bob.token })).status, 404);
assert.equal((await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: bob.token })).status, 404);
assert.equal(
(await api(srv.base, 'PATCH', `/api/projects/${p.id}`, { token: bob.token, body: { name: 'pirate' } })).status,
404,
);
assert.equal((await api(srv.base, 'DELETE', `/api/projects/${p.id}`, { token: bob.token })).status, 404);
assert.equal(
(await api(srv.base, 'POST', `/api/projects/${p.id}/chat`, { token: bob.token, body: { message: 'hi' } })).status,
404,
);
});
it('renames then deletes a project', async () => {
const p = await newProject('To rename');
const renamed = await api(srv.base, 'PATCH', `/api/projects/${p.id}`, {
token: alice.token,
body: { name: 'Renamed' },
});
assert.equal(renamed.json.project.name, 'Renamed');
assert.equal((await api(srv.base, 'DELETE', `/api/projects/${p.id}`, { token: alice.token })).status, 204);
assert.equal((await api(srv.base, 'GET', `/api/projects/${p.id}`, { token: alice.token })).status, 404);
});
it('handles the context (append, order, clear)', async () => {
const p = await newProject('Context');
await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, {
token: alice.token,
body: { role: 'system', content: 'Initial context' },
});
await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, {
token: alice.token,
body: { content: 'Hello Jarvis' },
});
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: alice.token });
assert.equal(msgs.json.messages.length, 2);
assert.equal(msgs.json.messages[0].content, 'Initial context');
assert.equal(msgs.json.messages[1].role, 'user');
assert.equal(
(await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, { token: alice.token, body: { content: '' } })).status,
400,
);
const cleared = await api(srv.base, 'DELETE', `/api/projects/${p.id}/messages`, { token: alice.token });
assert.equal(cleared.json.deleted, 2);
});
it('paginates the context', async () => {
const p = await newProject('Pagination');
for (let i = 1; i <= 5; i++) {
await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, {
token: alice.token,
body: { content: `message ${i}` },
});
}
const page1 = await api(srv.base, 'GET', `/api/projects/${p.id}/messages?limit=2`, { token: alice.token });
assert.deepEqual(
page1.json.messages.map((m) => m.content),
['message 4', 'message 5'],
);
assert.equal(page1.json.hasMore, true);
const page2 = await api(srv.base, 'GET', `/api/projects/${p.id}/messages?limit=2&before=${page1.json.oldestId}`, {
token: alice.token,
});
assert.deepEqual(
page2.json.messages.map((m) => m.content),
['message 2', 'message 3'],
);
assert.equal(page2.json.hasMore, true);
const page3 = await api(srv.base, 'GET', `/api/projects/${p.id}/messages?limit=2&before=${page2.json.oldestId}`, {
token: alice.token,
});
assert.deepEqual(
page3.json.messages.map((m) => m.content),
['message 1'],
);
assert.equal(page3.json.hasMore, false);
});
it('non-streamed chat: reply and context persistence', async () => {
const p = await newProject('Chat');
const res = await api(srv.base, 'POST', `/api/projects/${p.id}/chat`, {
token: alice.token,
body: { message: 'Hi' },
});
assert.equal(res.status, 200);
assert.equal(res.json.reply, 'Bonjour Tony, je suis Jarvis.');
assert.equal(res.json.messages.length, 2);
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: alice.token });
assert.equal(msgs.json.messages.length, 2);
assert.equal(msgs.json.messages[0].content, 'Hi');
assert.equal(msgs.json.messages[1].role, 'assistant');
const stats = await api(srv.base, 'GET', `/api/projects/${p.id}/stats`, { token: alice.token });
assert.equal(stats.json.stats.messageCount, 2);
});
it('Ollama error: no orphan message', async () => {
const p = await newProject('Error');
const res = await api(srv.base, 'POST', `/api/projects/${p.id}/chat`, {
token: alice.token,
body: { message: 'boom', model: 'boom' },
});
assert.ok(res.status >= 400);
assert.equal(
(await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: alice.token })).json.messages.length,
0,
);
});
});
+113
View File
@@ -0,0 +1,113 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { api, readSse, registerUser, startServer } from './helpers.js';
const FULL_REPLY = 'Bonjour Tony, je suis Jarvis.';
describe('streaming over SSE', () => {
let srv;
let user;
before(async () => {
srv = await startServer();
user = await registerUser(srv.base, 'stream@x.io');
});
after(async () => {
await srv.close();
});
async function newProject() {
const res = await api(srv.base, 'POST', '/api/projects', {
token: user.token,
body: { name: 'Stream' },
});
return res.json.project;
}
it('streams the answer chunk by chunk and persists at the end', async () => {
const p = await newProject();
const res = await fetch(`${srv.base}/api/projects/${p.id}/chat/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` },
body: JSON.stringify({ message: 'Hi' }),
});
assert.equal(res.status, 200);
assert.match(res.headers.get('content-type') ?? '', /text\/event-stream/);
const events = await readSse(res);
const deltas = events.filter((e) => e.event === 'delta').map((e) => e.data.content);
const done = events.find((e) => e.event === 'done');
assert.ok(deltas.length >= 5, `chunks received: ${deltas.length}`);
assert.equal(deltas.join(''), FULL_REPLY);
assert.ok(done, 'expected a done event');
assert.equal(done.data.reply, FULL_REPLY);
assert.equal(done.data.projectId, p.id);
assert.equal(done.data.messages.length, 2);
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: user.token });
assert.equal(msgs.json.messages.length, 2);
assert.equal(msgs.json.messages[1].content, FULL_REPLY);
});
it('injects the project context into the stream', async () => {
const p = await newProject();
await api(srv.base, 'POST', `/api/projects/${p.id}/messages`, {
token: user.token,
body: { role: 'system', content: 'Important note' },
});
const res = await fetch(`${srv.base}/api/projects/${p.id}/chat/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` },
body: JSON.stringify({ message: 'Follow up' }),
});
const events = await readSse(res);
assert.ok(events.some((e) => e.event === 'done'));
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: user.token });
assert.deepEqual(
msgs.json.messages.map((m) => m.content),
['Important note', 'Follow up', FULL_REPLY],
);
});
it('Ollama error before the stream: real HTTP error as JSON', async () => {
const p = await newProject();
const res = await fetch(`${srv.base}/api/projects/${p.id}/chat/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` },
body: JSON.stringify({ message: 'boom', model: 'boom' }),
});
assert.ok(res.status >= 400, `status: ${res.status}`);
assert.match(res.headers.get('content-type') ?? '', /application\/json/);
assert.ok((await res.json()).error);
const msgs = await api(srv.base, 'GET', `/api/projects/${p.id}/messages`, { token: user.token });
assert.equal(msgs.json.messages.length, 0, 'no orphan message');
});
it('stateless stream: requires authentication', async () => {
assert.equal((await fetch(`${srv.base}/api/chat/stream`, { method: 'POST' })).status, 401);
});
it('stateless stream: works', async () => {
const res = await fetch(`${srv.base}/api/chat/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${user.token}` },
body: JSON.stringify({ message: 'Hello' }),
});
assert.equal(res.status, 200);
const events = await readSse(res);
const deltas = events.filter((e) => e.event === 'delta').map((e) => e.data.content);
assert.equal(deltas.join(''), FULL_REPLY);
});
});