refactor(all): uniformisation

This commit is contained in:
BlackAngelTV committed 2026-09-23 18:25:28 +02:00
1 parent ee538cb943
commit 50665c8edd
89 files changed
+10215 -10215

No files matched your search

+222 -222
View File
@@ -1,222 +1,222 @@
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { UserFacingError } from '../src/core/errors.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
addBotStatus as addRow,
countBotStatuses,
getBotStatus,
listBotStatuses,
listEnabledBotStatuses,
removeBotStatus,
setBotStatusEnabled,
} from '../src/database/repositories/bot-status-repository.js';
import { setSetting } from '../src/database/repositories/settings-repository.js';
import {
addBotStatus,
applyStatusIfAlone,
clampRotation,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
getRotationSeconds,
normalizeStatusType,
ROTATION_KEY,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
rotateBotStatus,
sanitizeStatusText,
saveRotationSeconds,
selectNextStatus,
STATUS_MAX,
STATUS_TEXT_MAX,
statusListEmbed,
toggleBotStatus,
validateStatusUrl,
} from '../src/services/status/bot-status-service.js';
const GUILD = 'g';
describe('bot status repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM bot_statuses'));
it('stores a status and reads it back', () => {
const status = addRow({ text: 'les commandes avec /help', type: 'watching', createdBy: 'u1' });
assert.equal(status.text, 'les commandes avec /help');
assert.equal(status.type, 'watching');
assert.equal(status.enabled, 1);
assert.equal(status.created_by, 'u1');
assert.equal(getBotStatus(status.id).text, status.text);
assert.equal(countBotStatuses(), 1);
});
it('keeps the insertion order and separates the paused ones', () => {
const first = addRow({ text: 'un' });
addRow({ text: 'deux' });
const third = addRow({ text: 'trois' });
setBotStatusEnabled(third.id, false);
assert.deepEqual(
listBotStatuses().map((status) => status.text),
['un', 'deux', 'trois'],
);
assert.deepEqual(
listEnabledBotStatuses().map((status) => status.text),
['un', 'deux'],
);
assert.equal(first.id < third.id, true);
});
it('refuses the same text twice and forgets a removed status', () => {
const status = addRow({ text: 'déjà là' });
assert.throws(() => addRow({ text: 'déjà là' }), /UNIQUE constraint/i);
assert.equal(removeBotStatus(status.id), 1);
assert.equal(getBotStatus(status.id), null);
assert.equal(removeBotStatus(status.id), 0);
});
});
describe('bot status helpers', () => {
it('normalises the text and refuses what Discord would reject', () => {
assert.equal(sanitizeStatusText(' les tickets '), 'les tickets');
assert.equal(sanitizeStatusText('a\nb'), 'a b');
assert.equal(sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX)).length, STATUS_TEXT_MAX);
assert.throws(() => sanitizeStatusText(' '), UserFacingError);
assert.throws(() => sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX + 1)), UserFacingError);
});
it('accepts the known types and explains the others', () => {
assert.equal(normalizeStatusType(), 'watching');
assert.equal(normalizeStatusType('PLAYING'), 'playing');
assert.throws(() => normalizeStatusType('danse'), UserFacingError);
});
it('requires a link for a stream and validates the ones it gets', () => {
assert.throws(() => validateStatusUrl(null, 'streaming'), UserFacingError);
assert.throws(() => validateStatusUrl('twitch.tv/fws', 'streaming'), UserFacingError);
assert.equal(validateStatusUrl('https://twitch.tv/fws', 'streaming'), 'https://twitch.tv/fws');
assert.equal(validateStatusUrl(null, 'watching'), null);
assert.equal(validateStatusUrl('https://exemple.fr', 'playing'), 'https://exemple.fr');
});
it('formats a delay the way the embeds show it', () => {
assert.equal(formatSeconds(30), '30 s');
assert.equal(formatSeconds(60), '1 min');
assert.equal(formatSeconds(3600), '1 h');
assert.equal(formatSeconds(9000), '2 h 30 min');
});
});
describe('bot status rotation', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM bot_statuses');
getDatabase().exec(`DELETE FROM guild_settings WHERE key = '${ROTATION_KEY}'`);
});
const client = () => {
const presences = [];
return { presences, user: { setPresence: (payload) => presences.push(payload) } };
};
it('walks the enabled statuses one after the other, then starts over', () => {
const first = addBotStatus({ text: 'un' });
const second = addBotStatus({ text: 'deux' });
const third = addBotStatus({ text: 'trois', type: 'listening' });
setBotStatusEnabled(third.id, false);
const statuses = listEnabledBotStatuses();
assert.equal(selectNextStatus(statuses).id, first.id);
assert.equal(selectNextStatus(statuses, first.id).id, second.id);
assert.equal(selectNextStatus(statuses, second.id).id, first.id);
assert.equal(selectNextStatus([]), null);
});
it('shows the statuses in Discord with the right activity type', () => {
addBotStatus({ text: 'les tickets', type: 'listening' });
addBotStatus({ text: 'en direct', type: 'streaming', url: 'https://twitch.tv/fws' });
const fake = client();
const first = rotateBotStatus(fake);
const second = rotateBotStatus(fake, first.id);
assert.deepEqual(fake.presences[0].activities[0], { name: 'les tickets', type: 2 });
assert.equal(fake.presences[1].activities[0].url, 'https://twitch.tv/fws');
assert.equal(second.id !== first.id, true);
});
it('falls back to the default line instead of showing nothing', () => {
const fake = client();
assert.equal(rotateBotStatus(fake), FALLBACK_STATUS);
assert.equal(fake.presences[0].activities[0].name, FALLBACK_STATUS.text);
});
it('shows a lone status right away', () => {
const status = addBotStatus({ text: 'seul statut' });
const fake = client();
assert.equal(applyStatusIfAlone(fake).id, status.id);
addBotStatus({ text: 'un autre' });
assert.equal(applyStatusIfAlone(fake), null, 'with several statuses the rotation decides');
});
it('refuses the same text twice and stops at the maximum', () => {
addBotStatus({ text: 'unique' });
assert.throws(() => addBotStatus({ text: 'unique' }), UserFacingError);
for (let index = countBotStatuses(); index < STATUS_MAX; index += 1) {
addBotStatus({ text: `statut ${index}` });
}
assert.equal(countBotStatuses(), STATUS_MAX);
assert.throws(() => addBotStatus({ text: 'un de trop' }), UserFacingError);
});
it('pauses and resumes a status without losing it', () => {
const status = addBotStatus({ text: 'en pause' });
const paused = toggleBotStatus(status.id, false);
assert.equal(paused.enabled, 0);
assert.equal(listEnabledBotStatuses().length, 0);
assert.throws(() => toggleBotStatus(status.id, false), UserFacingError);
toggleBotStatus(status.id, true);
assert.equal(listEnabledBotStatuses()[0].id, status.id);
assert.throws(() => toggleBotStatus(999, true), UserFacingError);
});
it('empties the list and forgets every status', () => {
addBotStatus({ text: 'un' });
addBotStatus({ text: 'deux' });
assert.equal(clearBotStatusList(), 2);
assert.equal(countBotStatuses(), 0);
assert.equal(clearBotStatusList(), 0);
});
it('keeps the rotation delay between the allowed bounds, database first', () => {
assert.equal(clampRotation(30), 30);
assert.equal(clampRotation(ROTATION_MIN_SECONDS - 1), 60, 'an unusable value falls back to the default');
assert.equal(clampRotation(ROTATION_MAX_SECONDS + 1), 60);
assert.throws(() => clampRotation(1, { strict: true }), UserFacingError);
saveRotationSeconds(45, GUILD, 'u1');
assert.equal(getRotationSeconds(GUILD), 45);
setSetting(GUILD, ROTATION_KEY, 'pas un nombre', 'u1');
assert.equal(getRotationSeconds(GUILD), 60, 'a corrupted setting never breaks the rotation');
assert.equal(getRotationSeconds('autre-serveur'), 60);
});
it('lists the statuses with their state and the current rhythm', () => {
const empty = statusListEmbed({ guildId: GUILD, statuses: [] });
assert.match(empty.data.description, /Aucun statut personnalisé/);
const status = addBotStatus({ text: 'les commandes avec /help' });
const embed = statusListEmbed({ guildId: GUILD, statuses: listBotStatuses() });
assert.match(embed.data.description, /\*\*1\*\* statut\(s\), dont \*\*1\*\* en rotation/);
assert.equal(embed.data.fields[0].name, `#${status.id} · ✅ en rotation`);
assert.match(embed.data.fields[0].value, /les commandes avec \/help/);
});
});
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { UserFacingError } from '../src/core/errors.js';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
addBotStatus as addRow,
countBotStatuses,
getBotStatus,
listBotStatuses,
listEnabledBotStatuses,
removeBotStatus,
setBotStatusEnabled,
} from '../src/database/repositories/bot-status-repository.js';
import { setSetting } from '../src/database/repositories/settings-repository.js';
import {
addBotStatus,
applyStatusIfAlone,
clampRotation,
clearBotStatusList,
FALLBACK_STATUS,
formatSeconds,
getRotationSeconds,
normalizeStatusType,
ROTATION_KEY,
ROTATION_MAX_SECONDS,
ROTATION_MIN_SECONDS,
rotateBotStatus,
sanitizeStatusText,
saveRotationSeconds,
selectNextStatus,
STATUS_MAX,
STATUS_TEXT_MAX,
statusListEmbed,
toggleBotStatus,
validateStatusUrl,
} from '../src/services/status/bot-status-service.js';
const GUILD = 'g';
describe('bot status repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM bot_statuses'));
it('stores a status and reads it back', () => {
const status = addRow({ text: 'les commandes avec /help', type: 'watching', createdBy: 'u1' });
assert.equal(status.text, 'les commandes avec /help');
assert.equal(status.type, 'watching');
assert.equal(status.enabled, 1);
assert.equal(status.created_by, 'u1');
assert.equal(getBotStatus(status.id).text, status.text);
assert.equal(countBotStatuses(), 1);
});
it('keeps the insertion order and separates the paused ones', () => {
const first = addRow({ text: 'un' });
addRow({ text: 'deux' });
const third = addRow({ text: 'trois' });
setBotStatusEnabled(third.id, false);
assert.deepEqual(
listBotStatuses().map((status) => status.text),
['un', 'deux', 'trois'],
);
assert.deepEqual(
listEnabledBotStatuses().map((status) => status.text),
['un', 'deux'],
);
assert.equal(first.id < third.id, true);
});
it('refuses the same text twice and forgets a removed status', () => {
const status = addRow({ text: 'déjà là' });
assert.throws(() => addRow({ text: 'déjà là' }), /UNIQUE constraint/i);
assert.equal(removeBotStatus(status.id), 1);
assert.equal(getBotStatus(status.id), null);
assert.equal(removeBotStatus(status.id), 0);
});
});
describe('bot status helpers', () => {
it('normalises the text and refuses what Discord would reject', () => {
assert.equal(sanitizeStatusText(' les tickets '), 'les tickets');
assert.equal(sanitizeStatusText('a\nb'), 'a b');
assert.equal(sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX)).length, STATUS_TEXT_MAX);
assert.throws(() => sanitizeStatusText(' '), UserFacingError);
assert.throws(() => sanitizeStatusText('x'.repeat(STATUS_TEXT_MAX + 1)), UserFacingError);
});
it('accepts the known types and explains the others', () => {
assert.equal(normalizeStatusType(), 'watching');
assert.equal(normalizeStatusType('PLAYING'), 'playing');
assert.throws(() => normalizeStatusType('danse'), UserFacingError);
});
it('requires a link for a stream and validates the ones it gets', () => {
assert.throws(() => validateStatusUrl(null, 'streaming'), UserFacingError);
assert.throws(() => validateStatusUrl('twitch.tv/fws', 'streaming'), UserFacingError);
assert.equal(validateStatusUrl('https://twitch.tv/fws', 'streaming'), 'https://twitch.tv/fws');
assert.equal(validateStatusUrl(null, 'watching'), null);
assert.equal(validateStatusUrl('https://exemple.fr', 'playing'), 'https://exemple.fr');
});
it('formats a delay the way the embeds show it', () => {
assert.equal(formatSeconds(30), '30 s');
assert.equal(formatSeconds(60), '1 min');
assert.equal(formatSeconds(3600), '1 h');
assert.equal(formatSeconds(9000), '2 h 30 min');
});
});
describe('bot status rotation', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM bot_statuses');
getDatabase().exec(`DELETE FROM guild_settings WHERE key = '${ROTATION_KEY}'`);
});
const client = () => {
const presences = [];
return { presences, user: { setPresence: (payload) => presences.push(payload) } };
};
it('walks the enabled statuses one after the other, then starts over', () => {
const first = addBotStatus({ text: 'un' });
const second = addBotStatus({ text: 'deux' });
const third = addBotStatus({ text: 'trois', type: 'listening' });
setBotStatusEnabled(third.id, false);
const statuses = listEnabledBotStatuses();
assert.equal(selectNextStatus(statuses).id, first.id);
assert.equal(selectNextStatus(statuses, first.id).id, second.id);
assert.equal(selectNextStatus(statuses, second.id).id, first.id);
assert.equal(selectNextStatus([]), null);
});
it('shows the statuses in Discord with the right activity type', () => {
addBotStatus({ text: 'les tickets', type: 'listening' });
addBotStatus({ text: 'en direct', type: 'streaming', url: 'https://twitch.tv/fws' });
const fake = client();
const first = rotateBotStatus(fake);
const second = rotateBotStatus(fake, first.id);
assert.deepEqual(fake.presences[0].activities[0], { name: 'les tickets', type: 2 });
assert.equal(fake.presences[1].activities[0].url, 'https://twitch.tv/fws');
assert.equal(second.id !== first.id, true);
});
it('falls back to the default line instead of showing nothing', () => {
const fake = client();
assert.equal(rotateBotStatus(fake), FALLBACK_STATUS);
assert.equal(fake.presences[0].activities[0].name, FALLBACK_STATUS.text);
});
it('shows a lone status right away', () => {
const status = addBotStatus({ text: 'seul statut' });
const fake = client();
assert.equal(applyStatusIfAlone(fake).id, status.id);
addBotStatus({ text: 'un autre' });
assert.equal(applyStatusIfAlone(fake), null, 'with several statuses the rotation decides');
});
it('refuses the same text twice and stops at the maximum', () => {
addBotStatus({ text: 'unique' });
assert.throws(() => addBotStatus({ text: 'unique' }), UserFacingError);
for (let index = countBotStatuses(); index < STATUS_MAX; index += 1) {
addBotStatus({ text: `statut ${index}` });
}
assert.equal(countBotStatuses(), STATUS_MAX);
assert.throws(() => addBotStatus({ text: 'un de trop' }), UserFacingError);
});
it('pauses and resumes a status without losing it', () => {
const status = addBotStatus({ text: 'en pause' });
const paused = toggleBotStatus(status.id, false);
assert.equal(paused.enabled, 0);
assert.equal(listEnabledBotStatuses().length, 0);
assert.throws(() => toggleBotStatus(status.id, false), UserFacingError);
toggleBotStatus(status.id, true);
assert.equal(listEnabledBotStatuses()[0].id, status.id);
assert.throws(() => toggleBotStatus(999, true), UserFacingError);
});
it('empties the list and forgets every status', () => {
addBotStatus({ text: 'un' });
addBotStatus({ text: 'deux' });
assert.equal(clearBotStatusList(), 2);
assert.equal(countBotStatuses(), 0);
assert.equal(clearBotStatusList(), 0);
});
it('keeps the rotation delay between the allowed bounds, database first', () => {
assert.equal(clampRotation(30), 30);
assert.equal(clampRotation(ROTATION_MIN_SECONDS - 1), 60, 'an unusable value falls back to the default');
assert.equal(clampRotation(ROTATION_MAX_SECONDS + 1), 60);
assert.throws(() => clampRotation(1, { strict: true }), UserFacingError);
saveRotationSeconds(45, GUILD, 'u1');
assert.equal(getRotationSeconds(GUILD), 45);
setSetting(GUILD, ROTATION_KEY, 'pas un nombre', 'u1');
assert.equal(getRotationSeconds(GUILD), 60, 'a corrupted setting never breaks the rotation');
assert.equal(getRotationSeconds('autre-serveur'), 60);
});
it('lists the statuses with their state and the current rhythm', () => {
const empty = statusListEmbed({ guildId: GUILD, statuses: [] });
assert.match(empty.data.description, /Aucun statut personnalisé/);
const status = addBotStatus({ text: 'les commandes avec /help' });
const embed = statusListEmbed({ guildId: GUILD, statuses: listBotStatuses() });
assert.match(embed.data.description, /\*\*1\*\* statut\(s\), dont \*\*1\*\* en rotation/);
assert.equal(embed.data.fields[0].name, `#${status.id} · ✅ en rotation`);
assert.match(embed.data.fields[0].value, /les commandes avec \/help/);
});
});
+32 -32
View File
@@ -1,32 +1,32 @@
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js';
describe('database', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
it('applies the initial migration', () => {
const tables = getDatabase()
.prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
.all()
.map((row) => row.name);
assert.ok(tables.includes('tickets'));
assert.ok(tables.includes('guild_settings'));
});
it('isolates settings per guild', () => {
setSetting('guild-a', 'welcome', { enabled: true });
assert.deepEqual(getSetting('guild-a', 'welcome'), { enabled: true });
assert.equal(getSetting('guild-b', 'welcome'), null);
});
it('prevents two open tickets for the same author and category', () => {
const insert = getDatabase().prepare(
"INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')",
);
insert.run();
assert.throws(() => insert.run(), /UNIQUE/);
});
});
import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import { getSetting, setSetting } from '../src/database/repositories/settings-repository.js';
describe('database', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
it('applies the initial migration', () => {
const tables = getDatabase()
.prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
.all()
.map((row) => row.name);
assert.ok(tables.includes('tickets'));
assert.ok(tables.includes('guild_settings'));
});
it('isolates settings per guild', () => {
setSetting('guild-a', 'welcome', { enabled: true });
assert.deepEqual(getSetting('guild-a', 'welcome'), { enabled: true });
assert.equal(getSetting('guild-b', 'welcome'), null);
});
it('prevents two open tickets for the same author and category', () => {
const insert = getDatabase().prepare(
"INSERT INTO tickets (guild_id, category_id, author_id) VALUES ('g', 'bug', 'u')",
);
insert.run();
assert.throws(() => insert.run(), /UNIQUE/);
});
});
+50 -50
View File
@@ -1,50 +1,50 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8');
const headingCount = (text, level) => (text.match(new RegExp(`^${'#'.repeat(level)} `, 'gm')) ?? []).length;
const commandNames = (text) => new Set([...text.matchAll(/`\/([a-z]+)/g)].map((match) => match[1]));
const envTokens = (text) => new Set(text.match(/\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b/g) ?? []);
/** The organisation requires both READMEs, kept in sync (`.profile/README.md`). */
describe('bilingual documentation', () => {
it('keeps README.md and README.en.md structurally in sync', () => {
const fr = read('README.md');
const en = read('README.en.md');
assert.equal(headingCount(en, 2), headingCount(fr, 2), 'a section is missing on one side');
assert.equal(headingCount(en, 3), headingCount(fr, 3), 'a subsection is missing on one side');
});
it('documents the same commands and environment variables in both languages', () => {
const fr = read('README.md');
const en = read('README.en.md');
assert.deepEqual([...commandNames(en)].sort(), [...commandNames(fr)].sort(), 'command list differs');
assert.deepEqual([...envTokens(en)].sort(), [...envTokens(fr)].sort(), 'environment list differs');
});
it('links the two versions to each other', () => {
assert.match(read('README.md'), /README\.en\.md/, 'the French README does not link the English one');
assert.match(read('README.en.md'), /README\.md/, 'the English README does not link the French one');
});
it('ships the organisation files', () => {
assert.match(read('CHANGELOG.md'), /^# Changelog/, 'the generated changelog is missing');
assert.match(read('AGENTS.md'), /Instructions pour les agents/, 'the agent instructions are missing');
assert.match(
read('.gitea/PULL_REQUEST_TEMPLATE.md'),
/Conventional Commits/,
'the pull request template is missing',
);
assert.match(
read('.gitea/ISSUE_TEMPLATE/bug.md'),
/Étapes de reproduction/,
'the bug report template is missing',
);
assert.match(read('.gitignore'), /^\.env$/m, 'the environment files are not ignored');
assert.match(read('.gitignore'), /^\.freebuff\/$/m, 'the assistant data is not ignored');
});
});
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
const read = (file) => readFileSync(new URL(`../${file}`, import.meta.url), 'utf8');
const headingCount = (text, level) => (text.match(new RegExp(`^${'#'.repeat(level)} `, 'gm')) ?? []).length;
const commandNames = (text) => new Set([...text.matchAll(/`\/([a-z]+)/g)].map((match) => match[1]));
const envTokens = (text) => new Set(text.match(/\b[A-Z][A-Z0-9]*_[A-Z0-9_]+\b/g) ?? []);
/** The organisation requires both READMEs, kept in sync (`.profile/README.md`). */
describe('bilingual documentation', () => {
it('keeps README.md and README.en.md structurally in sync', () => {
const fr = read('README.md');
const en = read('README.en.md');
assert.equal(headingCount(en, 2), headingCount(fr, 2), 'a section is missing on one side');
assert.equal(headingCount(en, 3), headingCount(fr, 3), 'a subsection is missing on one side');
});
it('documents the same commands and environment variables in both languages', () => {
const fr = read('README.md');
const en = read('README.en.md');
assert.deepEqual([...commandNames(en)].sort(), [...commandNames(fr)].sort(), 'command list differs');
assert.deepEqual([...envTokens(en)].sort(), [...envTokens(fr)].sort(), 'environment list differs');
});
it('links the two versions to each other', () => {
assert.match(read('README.md'), /README\.en\.md/, 'the French README does not link the English one');
assert.match(read('README.en.md'), /README\.md/, 'the English README does not link the French one');
});
it('ships the organisation files', () => {
assert.match(read('CHANGELOG.md'), /^# Changelog/, 'the generated changelog is missing');
assert.match(read('AGENTS.md'), /Instructions pour les agents/, 'the agent instructions are missing');
assert.match(
read('.gitea/PULL_REQUEST_TEMPLATE.md'),
/Conventional Commits/,
'the pull request template is missing',
);
assert.match(
read('.gitea/ISSUE_TEMPLATE/bug.md'),
/Étapes de reproduction/,
'the bug report template is missing',
);
assert.match(read('.gitignore'), /^\.env$/m, 'the environment files are not ignored');
assert.match(read('.gitignore'), /^\.freebuff\/$/m, 'the assistant data is not ignored');
});
});
+108 -108
View File
@@ -1,108 +1,108 @@
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { readdir } from 'node:fs/promises';
import { describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { loadCommands } from '../src/core/command-loader.js';
const eventsDir = new URL('../src/events/', import.meta.url);
describe('command modules', () => {
it('exposes data, a valid access level and an execute function', async () => {
const commands = await loadCommands();
assert.ok(commands.length >= 16, `only ${commands.length} commands loaded`);
for (const command of commands) {
const json = command.data.toJSON();
assert.ok(json.name, 'a command has no name');
assert.ok(json.description, `/${json.name} has no description`);
assert.equal(typeof command.execute, 'function', `/${json.name} has no execute()`);
assert.ok(
Object.values(ACCESS_LEVELS).includes(command.access),
`/${json.name} has an unknown access level`,
);
}
});
it('uses unique command names', async () => {
const names = (await loadCommands()).map((command) => command.data.name);
assert.equal(new Set(names).size, names.length);
});
it('only overrides the access of declared subcommands', async () => {
/** Top-level subcommands and those nested in a subcommand group (M14). */
const subcommandNames = (options = []) =>
options.flatMap((option) =>
option.type === 1 ? [option.name] : option.type === 2 ? subcommandNames(option.options) : [],
);
for (const command of await loadCommands()) {
if (!command.subcommandAccess) continue;
const subcommands = subcommandNames(command.data.toJSON().options);
for (const name of Object.keys(command.subcommandAccess)) {
assert.ok(subcommands.includes(name), `/${command.data.name} ${name} is not a subcommand`);
}
}
});
});
describe('message tone', () => {
it('builds every embed with the shared titles, marker and hint', async () => {
const { TONE, bullets, errorEmbed, successEmbed, warningEmbed, withHint } =
await import('../src/ui/embeds.js');
assert.equal(successEmbed('x').data.title, TONE.success);
assert.equal(errorEmbed('x').data.title, TONE.error);
assert.equal(warningEmbed('x').data.title, TONE.warning);
assert.equal(bullets(['a', 'b', '']), '• a\n• b');
assert.equal(withHint('fait', 'ensuite'), 'fait\n\nensuite');
assert.equal(withHint('fait', null), 'fait');
});
it('keeps command descriptions free of gendered wording', async () => {
/** Words that would address or describe a person with a gender. */
const gendered =
/\b(utilisateur|utilisatrice|cher|chère|ravi|ravie|content|contente|bienvenu|bienvenue à (lui|elle))/i;
for (const command of await loadCommands()) {
const json = command.data.toJSON();
const texts = [json.description, ...(json.options ?? []).map((option) => option.description ?? '')];
for (const text of texts) {
assert.ok(!gendered.test(text), `/${json.name} uses gendered wording: ${text}`);
}
}
});
});
describe('webhook entry points', () => {
it('exposes the server and the dispatch functions', async () => {
const server = await import('../src/webhooks/server.js');
const webhook = await import('../src/webhooks/gitea-webhook.js');
assert.equal(typeof server.startWebhookServer, 'function');
assert.equal(typeof webhook.handleGiteaWebhook, 'function');
});
it('accepts only a valid HMAC signature and refuses an empty secret', async () => {
const { isValidSignature } = await import('../src/webhooks/gitea-webhook.js');
const body = Buffer.from('{"action":"opened"}');
const signature = createHmac('sha256', 'secret').update(body).digest('hex');
assert.equal(isValidSignature(body, signature, 'secret'), true);
assert.equal(isValidSignature(body, 'deadbeef', 'secret'), false);
assert.equal(isValidSignature(body, signature, ''), false);
assert.equal(isValidSignature(body, undefined, 'secret'), false);
});
});
describe('event modules', () => {
it('exports a name and a handler', async () => {
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
assert.ok(files.length >= 6, `only ${files.length} event files found`);
for (const file of files) {
const event = await import(new URL(file, eventsDir).href);
assert.equal(typeof event.name, 'string', `${file} has no name`);
assert.equal(typeof event.execute, 'function', `${file} has no execute()`);
}
});
});
import assert from 'node:assert/strict';
import { createHmac } from 'node:crypto';
import { readdir } from 'node:fs/promises';
import { describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { loadCommands } from '../src/core/command-loader.js';
const eventsDir = new URL('../src/events/', import.meta.url);
describe('command modules', () => {
it('exposes data, a valid access level and an execute function', async () => {
const commands = await loadCommands();
assert.ok(commands.length >= 16, `only ${commands.length} commands loaded`);
for (const command of commands) {
const json = command.data.toJSON();
assert.ok(json.name, 'a command has no name');
assert.ok(json.description, `/${json.name} has no description`);
assert.equal(typeof command.execute, 'function', `/${json.name} has no execute()`);
assert.ok(
Object.values(ACCESS_LEVELS).includes(command.access),
`/${json.name} has an unknown access level`,
);
}
});
it('uses unique command names', async () => {
const names = (await loadCommands()).map((command) => command.data.name);
assert.equal(new Set(names).size, names.length);
});
it('only overrides the access of declared subcommands', async () => {
/** Top-level subcommands and those nested in a subcommand group (M14). */
const subcommandNames = (options = []) =>
options.flatMap((option) =>
option.type === 1 ? [option.name] : option.type === 2 ? subcommandNames(option.options) : [],
);
for (const command of await loadCommands()) {
if (!command.subcommandAccess) continue;
const subcommands = subcommandNames(command.data.toJSON().options);
for (const name of Object.keys(command.subcommandAccess)) {
assert.ok(subcommands.includes(name), `/${command.data.name} ${name} is not a subcommand`);
}
}
});
});
describe('message tone', () => {
it('builds every embed with the shared titles, marker and hint', async () => {
const { TONE, bullets, errorEmbed, successEmbed, warningEmbed, withHint } =
await import('../src/ui/embeds.js');
assert.equal(successEmbed('x').data.title, TONE.success);
assert.equal(errorEmbed('x').data.title, TONE.error);
assert.equal(warningEmbed('x').data.title, TONE.warning);
assert.equal(bullets(['a', 'b', '']), '• a\n• b');
assert.equal(withHint('fait', 'ensuite'), 'fait\n\nensuite');
assert.equal(withHint('fait', null), 'fait');
});
it('keeps command descriptions free of gendered wording', async () => {
/** Words that would address or describe a person with a gender. */
const gendered =
/\b(utilisateur|utilisatrice|cher|chère|ravi|ravie|content|contente|bienvenu|bienvenue à (lui|elle))/i;
for (const command of await loadCommands()) {
const json = command.data.toJSON();
const texts = [json.description, ...(json.options ?? []).map((option) => option.description ?? '')];
for (const text of texts) {
assert.ok(!gendered.test(text), `/${json.name} uses gendered wording: ${text}`);
}
}
});
});
describe('webhook entry points', () => {
it('exposes the server and the dispatch functions', async () => {
const server = await import('../src/webhooks/server.js');
const webhook = await import('../src/webhooks/gitea-webhook.js');
assert.equal(typeof server.startWebhookServer, 'function');
assert.equal(typeof webhook.handleGiteaWebhook, 'function');
});
it('accepts only a valid HMAC signature and refuses an empty secret', async () => {
const { isValidSignature } = await import('../src/webhooks/gitea-webhook.js');
const body = Buffer.from('{"action":"opened"}');
const signature = createHmac('sha256', 'secret').update(body).digest('hex');
assert.equal(isValidSignature(body, signature, 'secret'), true);
assert.equal(isValidSignature(body, 'deadbeef', 'secret'), false);
assert.equal(isValidSignature(body, signature, ''), false);
assert.equal(isValidSignature(body, undefined, 'secret'), false);
});
});
describe('event modules', () => {
it('exports a name and a handler', async () => {
const files = (await readdir(eventsDir)).filter((file) => file.endsWith('.js'));
assert.ok(files.length >= 6, `only ${files.length} event files found`);
for (const file of files) {
const event = await import(new URL(file, eventsDir).href);
assert.equal(typeof event.name, 'string', `${file} has no name`);
assert.equal(typeof event.execute, 'function', `${file} has no execute()`);
}
});
});
+88 -88
View File
@@ -1,88 +1,88 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { buildGiteaNotification } from '../src/services/notifications/gitea-notifications.js';
import { releaseEmbed, truncate } from '../src/services/gitea/gitea-embeds.js';
const issue = {
number: 12,
title: 'Le lecteur ne démarre pas',
body: 'Depuis la mise à jour.',
state: 'open',
comments: 3,
user: { login: 'alice' },
html_url: 'https://gitea.example/FWS/FWS-Arch/issues/12',
labels: [{ name: 'bug' }],
};
describe('buildGiteaNotification', () => {
it('maps an issue event to the issues channel', () => {
const notification = buildGiteaNotification('issues', { issue });
assert.equal(notification.type, 'issues');
assert.equal(notification.embed.data.title, '#12 Le lecteur ne démarre pas');
assert.equal(notification.embed.data.url, issue.html_url);
});
it('maps a pull request to its own type', () => {
const notification = buildGiteaNotification('pull_request', {
pull_request: {
number: 4,
title: 'Corrige le démarrage',
state: 'open',
user: { login: 'bob' },
head: { ref: 'fix/boot' },
base: { ref: 'main' },
},
});
assert.equal(notification.type, 'pull_request');
assert.match(notification.embed.data.fields[2].value, /fix\/boot → main/);
});
it('reports a release with its tag', () => {
const notification = buildGiteaNotification('release', {
release: { tag_name: 'v1.2.0', name: 'Version 1.2.0', body: 'Nouveautés' },
});
assert.equal(notification.type, 'release');
assert.equal(notification.embed.data.title, 'Version 1.2.0');
});
it('ignores a push without commits', () => {
assert.equal(buildGiteaNotification('push', { commits: [], ref: 'refs/heads/main' }), null);
});
it('summarises the commits of a push', () => {
const notification = buildGiteaNotification('push', {
ref: 'refs/heads/main',
sender: { login: 'carol' },
commits: [{ id: 'abcdef1234567', message: 'fix: boot\n\nDétails' }],
});
assert.equal(notification.type, 'push');
assert.equal(notification.embed.data.title, 'Push sur main');
assert.match(notification.embed.data.description, /`abcdef1` fix: boot/);
});
it('ignores events without a notification type', () => {
assert.equal(buildGiteaNotification('repository', { repository: {} }), null);
});
});
describe('releaseEmbed', () => {
it('keeps the notes by default and can drop them', () => {
const release = {
tag_name: 'v2.0.0',
name: 'v2.0.0',
body: 'Changements',
published_at: '2026-01-01T10:00:00Z',
};
assert.equal(releaseEmbed(release).data.description, 'Changements');
assert.equal(releaseEmbed(release, { withNotes: false }).data.description, undefined);
});
});
describe('truncate', () => {
it('keeps short text and cuts long text', () => {
assert.equal(truncate('court'), 'court');
assert.equal(truncate('', 10), '');
assert.equal(truncate('ab'.repeat(20), 10).length, 10);
assert.match(truncate('ab'.repeat(20), 10), /…$/);
});
});
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { buildGiteaNotification } from '../src/services/notifications/gitea-notifications.js';
import { releaseEmbed, truncate } from '../src/services/gitea/gitea-embeds.js';
const issue = {
number: 12,
title: 'Le lecteur ne démarre pas',
body: 'Depuis la mise à jour.',
state: 'open',
comments: 3,
user: { login: 'alice' },
html_url: 'https://gitea.example/FWS/FWS-Arch/issues/12',
labels: [{ name: 'bug' }],
};
describe('buildGiteaNotification', () => {
it('maps an issue event to the issues channel', () => {
const notification = buildGiteaNotification('issues', { issue });
assert.equal(notification.type, 'issues');
assert.equal(notification.embed.data.title, '#12 Le lecteur ne démarre pas');
assert.equal(notification.embed.data.url, issue.html_url);
});
it('maps a pull request to its own type', () => {
const notification = buildGiteaNotification('pull_request', {
pull_request: {
number: 4,
title: 'Corrige le démarrage',
state: 'open',
user: { login: 'bob' },
head: { ref: 'fix/boot' },
base: { ref: 'main' },
},
});
assert.equal(notification.type, 'pull_request');
assert.match(notification.embed.data.fields[2].value, /fix\/boot → main/);
});
it('reports a release with its tag', () => {
const notification = buildGiteaNotification('release', {
release: { tag_name: 'v1.2.0', name: 'Version 1.2.0', body: 'Nouveautés' },
});
assert.equal(notification.type, 'release');
assert.equal(notification.embed.data.title, 'Version 1.2.0');
});
it('ignores a push without commits', () => {
assert.equal(buildGiteaNotification('push', { commits: [], ref: 'refs/heads/main' }), null);
});
it('summarises the commits of a push', () => {
const notification = buildGiteaNotification('push', {
ref: 'refs/heads/main',
sender: { login: 'carol' },
commits: [{ id: 'abcdef1234567', message: 'fix: boot\n\nDétails' }],
});
assert.equal(notification.type, 'push');
assert.equal(notification.embed.data.title, 'Push sur main');
assert.match(notification.embed.data.description, /`abcdef1` fix: boot/);
});
it('ignores events without a notification type', () => {
assert.equal(buildGiteaNotification('repository', { repository: {} }), null);
});
});
describe('releaseEmbed', () => {
it('keeps the notes by default and can drop them', () => {
const release = {
tag_name: 'v2.0.0',
name: 'v2.0.0',
body: 'Changements',
published_at: '2026-01-01T10:00:00Z',
};
assert.equal(releaseEmbed(release).data.description, 'Changements');
assert.equal(releaseEmbed(release, { withNotes: false }).data.description, undefined);
});
});
describe('truncate', () => {
it('keeps short text and cuts long text', () => {
assert.equal(truncate('court'), 'court');
assert.equal(truncate('', 10), '');
assert.equal(truncate('ab'.repeat(20), 10).length, 10);
assert.match(truncate('ab'.repeat(20), 10), /…$/);
});
});
+33 -33
View File
@@ -1,33 +1,33 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { consume, pendingCount, purgeExpired, remember } from '../src/services/gitea/pending-actions.js';
describe('pending actions', () => {
it('returns a stored value exactly once', () => {
remember('pr:1', { head: 'feature', base: 'main' });
assert.deepEqual(consume('pr:1'), { head: 'feature', base: 'main' });
assert.equal(consume('pr:1'), null);
});
it('returns null for an unknown key', () => {
assert.equal(consume('pr:unknown'), null);
});
it('drops an expired entry', () => {
const start = 1_000;
remember('pr:2', 'value', { ttlMs: 500, now: start });
assert.equal(consume('pr:2', { now: start + 501 }), null);
});
it('keeps a value still within its window', () => {
remember('pr:3', 'value', { ttlMs: 500, now: 0 });
assert.equal(consume('pr:3', { now: 499 }), 'value');
});
it('purges expired entries without touching fresh ones', () => {
remember('pr:4', 'old', { ttlMs: 10, now: 0 });
remember('pr:5', 'fresh', { ttlMs: 10_000, now: 0 });
assert.equal(purgeExpired(100), 1);
assert.equal(pendingCount(), 1);
});
});
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { consume, pendingCount, purgeExpired, remember } from '../src/services/gitea/pending-actions.js';
describe('pending actions', () => {
it('returns a stored value exactly once', () => {
remember('pr:1', { head: 'feature', base: 'main' });
assert.deepEqual(consume('pr:1'), { head: 'feature', base: 'main' });
assert.equal(consume('pr:1'), null);
});
it('returns null for an unknown key', () => {
assert.equal(consume('pr:unknown'), null);
});
it('drops an expired entry', () => {
const start = 1_000;
remember('pr:2', 'value', { ttlMs: 500, now: start });
assert.equal(consume('pr:2', { now: start + 501 }), null);
});
it('keeps a value still within its window', () => {
remember('pr:3', 'value', { ttlMs: 500, now: 0 });
assert.equal(consume('pr:3', { now: 499 }), 'value');
});
it('purges expired entries without touching fresh ones', () => {
remember('pr:4', 'old', { ttlMs: 10, now: 0 });
remember('pr:5', 'fresh', { ttlMs: 10_000, now: 0 });
assert.equal(purgeExpired(100), 1);
assert.equal(pendingCount(), 1);
});
});
+40 -40
View File
@@ -1,40 +1,40 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { getAccessLevel, hasAccess } from '../src/core/permissions.js';
const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' };
const fakeMember = (roleIds, { id = 'u1', ownerId = 'someone-else' } = {}) => ({
id,
guild: { ownerId },
roles: { cache: new Set(roleIds) },
});
describe('getAccessLevel', () => {
it('returns USER for a member without FWS roles', () => {
assert.equal(getAccessLevel(fakeMember(['r-member']), roles), ACCESS_LEVELS.USER);
});
it('returns the highest level when a member has several roles', () => {
assert.equal(getAccessLevel(fakeMember(['r-staff', 'r-dev']), roles), ACCESS_LEVELS.DEV);
});
it('returns OWNER for the guild owner', () => {
assert.equal(getAccessLevel(fakeMember([], { id: 'u1', ownerId: 'u1' }), roles), ACCESS_LEVELS.OWNER);
});
it('ignores unconfigured role ids', () => {
assert.equal(getAccessLevel(fakeMember(['']), { owner: '', dev: '', staff: '' }), ACCESS_LEVELS.USER);
});
});
describe('hasAccess', () => {
it('denies a staff command to a regular user', () => {
assert.equal(hasAccess(fakeMember([]), ACCESS_LEVELS.STAFF, roles), false);
});
it('allows a staff command to an owner', () => {
assert.equal(hasAccess(fakeMember(['r-owner']), ACCESS_LEVELS.STAFF, roles), true);
});
});
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { ACCESS_LEVELS } from '../src/config/constants.js';
import { getAccessLevel, hasAccess } from '../src/core/permissions.js';
const roles = { owner: 'r-owner', dev: 'r-dev', staff: 'r-staff', member: 'r-member' };
const fakeMember = (roleIds, { id = 'u1', ownerId = 'someone-else' } = {}) => ({
id,
guild: { ownerId },
roles: { cache: new Set(roleIds) },
});
describe('getAccessLevel', () => {
it('returns USER for a member without FWS roles', () => {
assert.equal(getAccessLevel(fakeMember(['r-member']), roles), ACCESS_LEVELS.USER);
});
it('returns the highest level when a member has several roles', () => {
assert.equal(getAccessLevel(fakeMember(['r-staff', 'r-dev']), roles), ACCESS_LEVELS.DEV);
});
it('returns OWNER for the guild owner', () => {
assert.equal(getAccessLevel(fakeMember([], { id: 'u1', ownerId: 'u1' }), roles), ACCESS_LEVELS.OWNER);
});
it('ignores unconfigured role ids', () => {
assert.equal(getAccessLevel(fakeMember(['']), { owner: '', dev: '', staff: '' }), ACCESS_LEVELS.USER);
});
});
describe('hasAccess', () => {
it('denies a staff command to a regular user', () => {
assert.equal(hasAccess(fakeMember([]), ACCESS_LEVELS.STAFF, roles), false);
});
it('allows a staff command to an owner', () => {
assert.equal(hasAccess(fakeMember(['r-owner']), ACCESS_LEVELS.STAFF, roles), true);
});
});
+80 -80
View File
@@ -1,80 +1,80 @@
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { formatDuration } from '../src/services/moderation/moderation-service.js';
import { buildPollEmbed, parseChoices, toSqliteDate } from '../src/services/polls/poll-service.js';
describe('parseChoices', () => {
it('splits, trims and keeps the order', () => {
assert.deepEqual(parseChoices('Oui ; Non; Peut-être '), ['Oui', 'Non', 'Peut-être']);
});
it('rejects a single choice', () => {
assert.throws(() => parseChoices('Oui'), /entre 2 et 10 propositions/);
});
it('rejects duplicated choices regardless of case', () => {
assert.throws(() => parseChoices('Oui;oui'), /Deux propositions identiques/);
});
it('rejects more choices than allowed', () => {
assert.throws(() => parseChoices(Array.from({ length: 11 }, (_v, i) => i).join(';')), /entre 2 et 10/);
});
});
describe('toSqliteDate', () => {
it('formats a UTC datetime the way SQLite stores it', () => {
assert.equal(toSqliteDate(new Date('2026-03-04T05:06:07.890Z')), '2026-03-04 05:06:07');
});
});
describe('buildPollEmbed', () => {
const poll = {
id: 3,
creator_id: 'u1',
question: 'Quel thème ?',
choices: JSON.stringify(['Clair', 'Sombre']),
status: 'open',
ends_at: null,
};
it('reports the totals and the percentage of each choice', () => {
const embed = buildPollEmbed(poll, [
{ choice_index: 0, count: 3 },
{ choice_index: 1, count: 1 },
]);
assert.equal(embed.data.title, '📊 Sondage #3 — Quel thème ?');
assert.match(embed.data.description, /Clair/);
assert.match(embed.data.description, /3 \(75 %\)/);
assert.equal(embed.data.fields[0].value, '4');
});
it('handles a poll without any vote', () => {
const embed = buildPollEmbed(poll, []);
assert.match(embed.data.description, /0 \(0 %\)/);
assert.equal(embed.data.fields[0].value, '0');
});
it('announces the winning choice once closed', () => {
const closed = { ...poll, status: 'closed' };
const embed = buildPollEmbed(closed, [
{ choice_index: 0, count: 1 },
{ choice_index: 1, count: 5 },
]);
assert.equal(embed.data.fields.at(-1).value, '**Sombre** (5 vote(s))');
});
it('says so when a closed poll has no vote', () => {
const embed = buildPollEmbed({ ...poll, status: 'closed' }, []);
assert.equal(embed.data.fields.at(-1).value, 'Aucun vote');
});
});
describe('formatDuration', () => {
it('formats minutes, hours and days', () => {
assert.equal(formatDuration(30 * 60_000), '30 min');
assert.equal(formatDuration(60 * 60_000), '1 h');
assert.equal(formatDuration(150 * 60_000), '2 h 30 min');
assert.equal(formatDuration(24 * 60 * 60_000), '1 j');
assert.equal(formatDuration(30 * 60 * 60_000), '1 j 6 h');
});
});
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { formatDuration } from '../src/services/moderation/moderation-service.js';
import { buildPollEmbed, parseChoices, toSqliteDate } from '../src/services/polls/poll-service.js';
describe('parseChoices', () => {
it('splits, trims and keeps the order', () => {
assert.deepEqual(parseChoices('Oui ; Non; Peut-être '), ['Oui', 'Non', 'Peut-être']);
});
it('rejects a single choice', () => {
assert.throws(() => parseChoices('Oui'), /entre 2 et 10 propositions/);
});
it('rejects duplicated choices regardless of case', () => {
assert.throws(() => parseChoices('Oui;oui'), /Deux propositions identiques/);
});
it('rejects more choices than allowed', () => {
assert.throws(() => parseChoices(Array.from({ length: 11 }, (_v, i) => i).join(';')), /entre 2 et 10/);
});
});
describe('toSqliteDate', () => {
it('formats a UTC datetime the way SQLite stores it', () => {
assert.equal(toSqliteDate(new Date('2026-03-04T05:06:07.890Z')), '2026-03-04 05:06:07');
});
});
describe('buildPollEmbed', () => {
const poll = {
id: 3,
creator_id: 'u1',
question: 'Quel thème ?',
choices: JSON.stringify(['Clair', 'Sombre']),
status: 'open',
ends_at: null,
};
it('reports the totals and the percentage of each choice', () => {
const embed = buildPollEmbed(poll, [
{ choice_index: 0, count: 3 },
{ choice_index: 1, count: 1 },
]);
assert.equal(embed.data.title, '📊 Sondage #3 — Quel thème ?');
assert.match(embed.data.description, /Clair/);
assert.match(embed.data.description, /3 \(75 %\)/);
assert.equal(embed.data.fields[0].value, '4');
});
it('handles a poll without any vote', () => {
const embed = buildPollEmbed(poll, []);
assert.match(embed.data.description, /0 \(0 %\)/);
assert.equal(embed.data.fields[0].value, '0');
});
it('announces the winning choice once closed', () => {
const closed = { ...poll, status: 'closed' };
const embed = buildPollEmbed(closed, [
{ choice_index: 0, count: 1 },
{ choice_index: 1, count: 5 },
]);
assert.equal(embed.data.fields.at(-1).value, '**Sombre** (5 vote(s))');
});
it('says so when a closed poll has no vote', () => {
const embed = buildPollEmbed({ ...poll, status: 'closed' }, []);
assert.equal(embed.data.fields.at(-1).value, 'Aucun vote');
});
});
describe('formatDuration', () => {
it('formats minutes, hours and days', () => {
assert.equal(formatDuration(30 * 60_000), '30 min');
assert.equal(formatDuration(60 * 60_000), '1 h');
assert.equal(formatDuration(150 * 60_000), '2 h 30 min');
assert.equal(formatDuration(24 * 60 * 60_000), '1 j');
assert.equal(formatDuration(30 * 60 * 60_000), '1 j 6 h');
});
});
+189 -189
View File
@@ -1,189 +1,189 @@
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
countActions,
listActions,
recordAction,
} from '../src/database/repositories/moderation-repository.js';
import {
getNotificationChannel,
removeNotificationChannel,
setNotificationChannel,
} from '../src/database/repositories/notification-repository.js';
import {
castVote,
closePoll,
countVotes,
createPoll,
listDuePolls,
} from '../src/database/repositories/poll-repository.js';
import {
claimTicket,
closeTicket,
countOpenTickets,
createTicket,
getOpenTicket,
getTicketByChannel,
} from '../src/database/repositories/ticket-repository.js';
const reset = () =>
getDatabase().exec(
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;',
);
describe('ticket repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
const openTicket = () => createTicket({ guildId: 'g', channelId: 'c1', categoryId: 'bug', authorId: 'u1' });
it('creates a ticket and finds it by channel', () => {
const id = openTicket();
const ticket = getTicketByChannel('c1');
assert.equal(ticket.id, id);
assert.equal(ticket.status, 'open');
assert.equal(ticket.claimed_by, null);
});
it('refuses a second open ticket for the same author and category', () => {
openTicket();
assert.throws(
() => createTicket({ guildId: 'g', channelId: 'c2', categoryId: 'bug', authorId: 'u1' }),
/UNIQUE/,
);
assert.equal(getOpenTicket({ guildId: 'g', authorId: 'u1', categoryId: 'bug' }).channel_id, 'c1');
});
it('allows a new ticket once the previous one is closed', () => {
const id = openTicket();
closeTicket(id, { closedBy: 'staff', reason: 'résolu' });
const newId = createTicket({ guildId: 'g', channelId: 'c3', categoryId: 'bug', authorId: 'u1' });
assert.notEqual(newId, id);
assert.equal(countOpenTickets('g'), 1);
});
it('records who claimed and closed a ticket', () => {
const id = openTicket();
assert.equal(claimTicket(id, 'staff'), 1);
assert.equal(getTicketByChannel('c1').claimed_by, 'staff');
assert.equal(closeTicket(id, { closedBy: 'staff', reason: 'ok' }), 1);
const closed = getTicketByChannel('c1');
assert.equal(closed.status, 'closed');
assert.equal(closed.close_reason, 'ok');
assert.ok(closed.closed_at);
});
it('cannot close a ticket twice', () => {
const id = openTicket();
closeTicket(id, { closedBy: 'staff' });
assert.equal(closeTicket(id, { closedBy: 'staff' }), 0);
});
});
describe('moderation repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
it('records and lists actions of a target', () => {
recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'spam' });
recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'again' });
recordAction({ guildId: 'g', action: 'kick', moderatorId: 'm2', targetId: 'u2' });
assert.equal(countActions({ guildId: 'g', targetId: 'u1', action: 'warn' }), 2);
const history = listActions({ guildId: 'g', targetId: 'u1' });
assert.equal(history.length, 2);
assert.equal(history[0].reason, 'again');
assert.equal(listActions({ guildId: 'g', action: 'kick' }).length, 1);
});
it('keeps the duration of a mute', () => {
recordAction({
guildId: 'g',
action: 'mute',
moderatorId: 'm1',
targetId: 'u1',
durationMs: 60_000,
});
assert.equal(listActions({ guildId: 'g', targetId: 'u1' })[0].duration_ms, 60_000);
});
});
describe('poll repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
const poll = () =>
createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'Question ?',
choices: ['a', 'b'],
endsAt: null,
});
it('counts one vote per user and allows a change of mind', () => {
const id = poll();
assert.equal(castVote(id, 'u1', 0), 'created');
assert.equal(castVote(id, 'u1', 0), 'unchanged');
assert.equal(castVote(id, 'u1', 1), 'changed');
assert.equal(castVote(id, 'u2', 1), 'created');
const counts = countVotes(id);
assert.equal(counts.length, 1);
assert.deepEqual({ ...counts[0] }, { choice_index: 1, count: 2 });
});
it('lists only the polls whose end date has passed', () => {
const due = createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'Bientôt fini',
choices: ['a', 'b'],
endsAt: '2000-01-01 00:00:00',
});
createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'En cours',
choices: ['a', 'b'],
endsAt: '2999-01-01 00:00:00',
});
const ids = listDuePolls().map((row) => row.id);
assert.deepEqual(ids, [due]);
});
it('closes a poll only once', () => {
const id = poll();
assert.equal(closePoll(id), 1);
assert.equal(closePoll(id), 0);
});
});
describe('notification repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
it('stores one channel per type and replaces it', () => {
setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c1' });
setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c2' });
assert.equal(getNotificationChannel('g', 'issues').channel_id, 'c2');
assert.equal(getNotificationChannel('other', 'issues'), null);
});
it('removes an override and reports it', () => {
setNotificationChannel({ guildId: 'g', type: 'release', channelId: 'c1' });
assert.equal(removeNotificationChannel('g', 'release'), 1);
assert.equal(removeNotificationChannel('g', 'release'), 0);
});
});
import assert from 'node:assert/strict';
import { after, before, beforeEach, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
countActions,
listActions,
recordAction,
} from '../src/database/repositories/moderation-repository.js';
import {
getNotificationChannel,
removeNotificationChannel,
setNotificationChannel,
} from '../src/database/repositories/notification-repository.js';
import {
castVote,
closePoll,
countVotes,
createPoll,
listDuePolls,
} from '../src/database/repositories/poll-repository.js';
import {
claimTicket,
closeTicket,
countOpenTickets,
createTicket,
getOpenTicket,
getTicketByChannel,
} from '../src/database/repositories/ticket-repository.js';
const reset = () =>
getDatabase().exec(
'DELETE FROM tickets; DELETE FROM moderation_actions; DELETE FROM polls; DELETE FROM poll_votes; DELETE FROM notification_channels;',
);
describe('ticket repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
const openTicket = () => createTicket({ guildId: 'g', channelId: 'c1', categoryId: 'bug', authorId: 'u1' });
it('creates a ticket and finds it by channel', () => {
const id = openTicket();
const ticket = getTicketByChannel('c1');
assert.equal(ticket.id, id);
assert.equal(ticket.status, 'open');
assert.equal(ticket.claimed_by, null);
});
it('refuses a second open ticket for the same author and category', () => {
openTicket();
assert.throws(
() => createTicket({ guildId: 'g', channelId: 'c2', categoryId: 'bug', authorId: 'u1' }),
/UNIQUE/,
);
assert.equal(getOpenTicket({ guildId: 'g', authorId: 'u1', categoryId: 'bug' }).channel_id, 'c1');
});
it('allows a new ticket once the previous one is closed', () => {
const id = openTicket();
closeTicket(id, { closedBy: 'staff', reason: 'résolu' });
const newId = createTicket({ guildId: 'g', channelId: 'c3', categoryId: 'bug', authorId: 'u1' });
assert.notEqual(newId, id);
assert.equal(countOpenTickets('g'), 1);
});
it('records who claimed and closed a ticket', () => {
const id = openTicket();
assert.equal(claimTicket(id, 'staff'), 1);
assert.equal(getTicketByChannel('c1').claimed_by, 'staff');
assert.equal(closeTicket(id, { closedBy: 'staff', reason: 'ok' }), 1);
const closed = getTicketByChannel('c1');
assert.equal(closed.status, 'closed');
assert.equal(closed.close_reason, 'ok');
assert.ok(closed.closed_at);
});
it('cannot close a ticket twice', () => {
const id = openTicket();
closeTicket(id, { closedBy: 'staff' });
assert.equal(closeTicket(id, { closedBy: 'staff' }), 0);
});
});
describe('moderation repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
it('records and lists actions of a target', () => {
recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'spam' });
recordAction({ guildId: 'g', action: 'warn', moderatorId: 'm1', targetId: 'u1', reason: 'again' });
recordAction({ guildId: 'g', action: 'kick', moderatorId: 'm2', targetId: 'u2' });
assert.equal(countActions({ guildId: 'g', targetId: 'u1', action: 'warn' }), 2);
const history = listActions({ guildId: 'g', targetId: 'u1' });
assert.equal(history.length, 2);
assert.equal(history[0].reason, 'again');
assert.equal(listActions({ guildId: 'g', action: 'kick' }).length, 1);
});
it('keeps the duration of a mute', () => {
recordAction({
guildId: 'g',
action: 'mute',
moderatorId: 'm1',
targetId: 'u1',
durationMs: 60_000,
});
assert.equal(listActions({ guildId: 'g', targetId: 'u1' })[0].duration_ms, 60_000);
});
});
describe('poll repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
const poll = () =>
createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'Question ?',
choices: ['a', 'b'],
endsAt: null,
});
it('counts one vote per user and allows a change of mind', () => {
const id = poll();
assert.equal(castVote(id, 'u1', 0), 'created');
assert.equal(castVote(id, 'u1', 0), 'unchanged');
assert.equal(castVote(id, 'u1', 1), 'changed');
assert.equal(castVote(id, 'u2', 1), 'created');
const counts = countVotes(id);
assert.equal(counts.length, 1);
assert.deepEqual({ ...counts[0] }, { choice_index: 1, count: 2 });
});
it('lists only the polls whose end date has passed', () => {
const due = createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'Bientôt fini',
choices: ['a', 'b'],
endsAt: '2000-01-01 00:00:00',
});
createPoll({
guildId: 'g',
channelId: 'c',
creatorId: 'u1',
question: 'En cours',
choices: ['a', 'b'],
endsAt: '2999-01-01 00:00:00',
});
const ids = listDuePolls().map((row) => row.id);
assert.deepEqual(ids, [due]);
});
it('closes a poll only once', () => {
const id = poll();
assert.equal(closePoll(id), 1);
assert.equal(closePoll(id), 0);
});
});
describe('notification repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(reset);
it('stores one channel per type and replaces it', () => {
setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c1' });
setNotificationChannel({ guildId: 'g', type: 'issues', channelId: 'c2' });
assert.equal(getNotificationChannel('g', 'issues').channel_id, 'c2');
assert.equal(getNotificationChannel('other', 'issues'), null);
});
it('removes an override and reports it', () => {
setNotificationChannel({ guildId: 'g', type: 'release', channelId: 'c1' });
assert.equal(removeNotificationChannel('g', 'release'), 1);
assert.equal(removeNotificationChannel('g', 'release'), 0);
});
});
+530 -530
View File
File diff suppressed because it is too large. Load diff