Files
FWS-DiscordBot/tests/web-deployments.test.js
nocodeandClaude Opus 5 bd7fdea275 test(web): cover the router, configuration, auth, deployments and server
The schema test compares the declared variables against `.env.example`, so
the two cannot drift apart. The server tests drive the real handler over a
loopback socket rather than a mock, which is what caught the health probe
missing from bootstrap mode and the deployments recorded under the wrong
guild.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:09:14 +02:00

225 lines
7.9 KiB
JavaScript

import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { createServer } from 'node:http';
import { after, afterEach, before, beforeEach, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
countByStatus,
createTarget,
getTarget,
listAutoTargets,
listDeployments,
listTargets,
removeTarget,
updateTarget,
} from '../src/database/repositories/deploy-repository.js';
import { splitRepository } from '../src/services/gitea/gitea-admin.js';
import { assertRunnable, describeTarget, runDeployment } from '../src/web/services/deploy-service.js';
const GUILD = 'guild-1';
const webhookTarget = (overrides = {}) =>
createTarget({
guildId: GUILD,
name: 'production',
repository: 'FWS/FWS-Arch',
environment: 'production',
kind: 'webhook',
config: { url: 'http://127.0.0.1:1/hook', secret: 'partage' },
...overrides,
});
describe('deploy repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;'));
it('stores and reads back a target with its parsed config', () => {
const target = webhookTarget();
assert.equal(target.config.url, 'http://127.0.0.1:1/hook');
assert.equal(target.enabled, true);
assert.equal(target.auto_deploy, false);
assert.deepEqual(getTarget(target.id), target);
});
it('filters targets by repository', () => {
webhookTarget();
webhookTarget({ name: 'site', repository: 'FWS/site' });
assert.equal(listTargets({ guildId: GUILD }).length, 2);
assert.equal(listTargets({ guildId: GUILD, repository: 'FWS/site' }).length, 1);
});
it('only returns enabled auto-deploy targets', () => {
webhookTarget({ name: 'manuel' });
webhookTarget({ name: 'auto', autoDeploy: true });
webhookTarget({ name: 'auto-en-pause', autoDeploy: true, enabled: false });
const auto = listAutoTargets({ guildId: GUILD, repository: 'FWS/FWS-Arch' });
assert.deepEqual(
auto.map((target) => target.name),
['auto'],
);
});
it('updates only the known columns', () => {
const target = webhookTarget();
// The repository speaks in column names; the API layer does the translation.
const updated = updateTarget(target.id, { environment: 'staging', bogus: 'ignoré', auto_deploy: true });
assert.equal(updated.environment, 'staging');
assert.equal(updated.auto_deploy, true);
assert.equal(updated.bogus, undefined);
assert.ok(updated.updated_at);
});
it('keeps the history when its target is deleted', async () => {
const target = webhookTarget();
await runDeployment(null, target, { ref: 'main' }).catch(() => null);
removeTarget(target.id);
const [deployment] = listDeployments({ guildId: GUILD });
assert.equal(deployment.target_id, null);
assert.equal(deployment.target_name, 'production');
});
it('describes a target in one line', () => {
assert.match(describeTarget(webhookTarget()), /^POST http/);
assert.equal(
describeTarget({ kind: 'gitea-action', config: { workflow: 'deploy.yml', ref: 'main' } }),
'workflow deploy.yml sur main',
);
});
});
describe('deploy guards', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;'));
it('refuses a disabled target', () => {
assert.throws(() => assertRunnable(webhookTarget({ enabled: false })), { status: 400 });
});
it('refuses a webhook target with no url', () => {
assert.throws(() => assertRunnable(webhookTarget({ config: {} })), { status: 400 });
});
it('refuses a command target while command deploys are off', () => {
const target = webhookTarget({ name: 'shell', kind: 'command', config: { command: 'echo bonjour' } });
// `WEB_ALLOW_COMMAND_DEPLOYS` is unset in the tests, so this must be blocked.
assert.throws(() => assertRunnable(target), { status: 403 });
});
it('refuses an unknown kind', () => {
assert.throws(() => assertRunnable({ enabled: true, kind: 'magic', config: {} }), { status: 400 });
});
});
describe('webhook deployments', () => {
let server;
let received;
let reply;
before(async () => {
initDatabase(':memory:');
server = createServer((request, response) => {
let body = '';
request.on('data', (chunk) => (body += chunk));
request.on('end', () => {
received = { headers: request.headers, body };
response.writeHead(reply.status, { 'Content-Type': 'text/plain' }).end(reply.body);
});
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
});
after(async () => {
await new Promise((resolve) => server.close(resolve));
closeDatabase();
});
beforeEach(() => {
getDatabase().exec('DELETE FROM deployments; DELETE FROM deploy_targets;');
received = null;
reply = { status: 200, body: 'déployé' };
});
afterEach(() => {
received = null;
});
const url = () => `http://127.0.0.1:${server.address().port}/hook`;
it('calls the webhook and records a success', async () => {
const target = webhookTarget({ config: { url: url(), secret: 'partage' } });
const deployment = await runDeployment(null, target, { releaseTag: 'v1.0.0', triggeredBy: 'u1' });
assert.equal(deployment.status, 'success');
assert.match(deployment.log, /déployé/);
const [stored] = listDeployments({ guildId: 'guild-1' });
assert.equal(stored.status, 'success');
assert.equal(stored.release_tag, 'v1.0.0');
assert.ok(stored.finished_at);
});
it('signs the payload with the shared secret', async () => {
const target = webhookTarget({ config: { url: url(), secret: 'partage' } });
await runDeployment(null, target, { ref: 'main' });
const expected = createHmac('sha256', 'partage').update(received.body).digest('hex');
assert.equal(received.headers['x-fws-signature'], expected);
});
it('sends the deployment context in the body', async () => {
const target = webhookTarget({ config: { url: url() } });
await runDeployment(null, target, { releaseTag: 'v2.0.0', ref: 'main', triggeredBy: 'u9' });
const payload = JSON.parse(received.body);
assert.equal(payload.repository, 'FWS/FWS-Arch');
assert.equal(payload.environment, 'production');
assert.equal(payload.releaseTag, 'v2.0.0');
assert.equal(payload.triggeredBy, 'u9');
});
it('omits the signature when no secret is configured', async () => {
const target = webhookTarget({ config: { url: url() } });
await runDeployment(null, target, {});
assert.equal(received.headers['x-fws-signature'], undefined);
});
it('records a failure when the endpoint answers with an error', async () => {
reply = { status: 500, body: 'boum' };
const target = webhookTarget({ config: { url: url() } });
const deployment = await runDeployment(null, target, {});
assert.equal(deployment.status, 'failed');
assert.match(deployment.error, /500/);
assert.match(deployment.log, /boum/);
});
it('counts the deployments by status', async () => {
const ok = webhookTarget({ name: 'ok', config: { url: url() } });
await runDeployment(null, ok, {});
reply = { status: 503, body: '' };
await runDeployment(null, ok, {});
const counts = Object.fromEntries(countByStatus('guild-1').map((row) => [row.status, row.count]));
assert.equal(counts.success, 1);
assert.equal(counts.failed, 1);
});
});
describe('repository names', () => {
it('splits a full name', () => {
assert.deepEqual(splitRepository('FWS/FWS-Arch'), { owner: 'FWS', repo: 'FWS-Arch' });
});
it('rejects anything that is not exactly owner/repo', () => {
assert.equal(splitRepository('FWS'), null);
assert.equal(splitRepository('FWS/Arch/extra'), null);
assert.equal(splitRepository(''), null);
assert.equal(splitRepository(undefined), null);
});
});