test(aep-surface): banc qui joue les routes bâties contre un faux serveur local (étape A)

npm run test:routes bâtit l'application, la démarre sur un port local avec un
environnement vide, et joue des requêtes HTTP. NocoDB, Bifrost, Mistral, Resend
et LightRAG sont remplacés par un faux serveur qui enregistre ce qu'il reçoit.
Adresses Resend et Mistral et dossier des limites de débit réglables par
l'environnement (RESEND_API_URL, MISTRAL_API_URL, NAV_RATELIMIT_DIR), valeur
d'aujourd'hui par défaut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jules
2026-11-22 11:10:56 +01:00
co-authored by Claude Opus 5.5
parent f40fcd8747
commit ff22377619
7 changed files with 320 additions and 4 deletions
+250
View File
@@ -0,0 +1,250 @@
/**
* Banc de routes (lot SURFACE, étape A) : le serveur Nuxt BÂTI (`.output/server/index.mjs`)
* démarré sur un port local, tous ses services externes remplacés par UN faux serveur local
* qui enregistre ce qu'il reçoit et répond ce qu'on lui dit.
*
* Aucun appel réel : l'application démarre avec un environnement VIDE (pas celui du shell,
* pas de .env), où chaque adresse de service pointe le faux serveur et chaque clé vaut « faux ».
*
* Usage (voir scripts/test-routes.mjs) :
* import { demarrerBanc } from './banc-routes.mjs'
* const banc = await demarrerBanc() // bâtit si besoin, démarre faux + appli
* banc.faux.repondre.bifrost = (req) => ({ json: { … } })
* const r = await banc.requete('/api/chatbot', { method: 'POST', json: { question: '…' }, ip: '10.0.0.1' })
* banc.faux.recu('resend') // requêtes reçues par le faux Resend
* await banc.arreter()
*
* Services simulés (préfixe d'URL sur le faux serveur → variable d'environnement de l'appli) :
* /nocodb → NUXT_NOCODB_URL GET/POST /api/v2/tables/:table/records
* /bifrost → NUXT_BIFROST_URL POST /v1/chat/completions
* /mistral → MISTRAL_API_URL POST /v1/chat/completions (filtre des commentaires)
* /resend → RESEND_API_URL POST /emails (signalements)
* /rag → NUXT_RAG_PE_URL GET /health, POST /query (LightRAG Pensées)
* /rag-emancipation → NUXT_RAG_EMANCIPATION_URL
* Redis pointe un port fermé : la limite de débit Redis retombe sur son compteur en mémoire.
*/
import { spawn, spawnSync } from 'node:child_process'
import { createServer } from 'node:http'
import { existsSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const RACINE = join(dirname(fileURLToPath(import.meta.url)), '..')
const TABLES = { orgs: 'tbl_orgs', stats: 'tbl_stats', comments: 'tbl_comments', avis: 'tbl_avis' }
function lireCorps(req) {
return new Promise((resolve) => {
const morceaux = []
req.on('data', (c) => morceaux.push(c))
req.on('end', () => {
const brut = Buffer.concat(morceaux).toString('utf-8')
let json = null
try { json = brut ? JSON.parse(brut) : null } catch { /* corps non JSON */ }
resolve({ brut, json })
})
})
}
/** Réponse Bifrost par défaut : un JSON valide, servi par un fournisseur gratuit. */
export function reponseBifrost(contenu = { reponse_texte: 'Réponse du faux modèle.', fiches_recommandees: [] }, extra = {}) {
return {
json: {
choices: [{ message: { content: typeof contenu === 'string' ? contenu : JSON.stringify(contenu) }, finish_reason: 'stop' }],
usage: { prompt_tokens: 1000, completion_tokens: 200 },
extra_fields: { provider: 'groq', resolved_model_used: 'groq/openai/gpt-oss-20b' },
...extra,
},
}
}
/** Réponse Mistral (filtre des commentaires) dont le `content` vaut `contenu` tel quel. */
export function reponseMistral(contenu) {
return { json: { choices: [{ message: { content: contenu } }] } }
}
function fauxParDefaut() {
return {
nocodb: (req) => {
const m = req.chemin.match(/^\/api\/v2\/tables\/([^/]+)\/records/)
if (!m) return { status: 404, json: { msg: 'faux NocoDB : chemin inconnu' } }
if (req.methode === 'GET') {
const lignes = m[1] === TABLES.orgs ? [{ Id: 1, nom: 'Organisation témoin', description_enrichie: 'architecture paille', tags_fonction: 'Conseil', echelle: 'Locale', localisation_ville: 'Lyon' }] : []
return { json: { list: lignes, pageInfo: { isLastPage: true } } }
}
return { json: { Id: 42 } }
},
bifrost: () => reponseBifrost(),
mistral: () => reponseMistral('{"safe": true, "category": null, "reason": null}'),
resend: () => ({ json: { id: 'faux-courriel' } }),
rag: (req) => (req.chemin === '/health' ? { json: { status: 'healthy' } } : { json: { response: 'Réponse du faux RAG.', references: [] } }),
'rag-emancipation': (req) => (req.chemin === '/health' ? { json: { status: 'healthy' } } : { json: { response: 'Réponse du faux RAG Émancipation.', references: [] } }),
}
}
/** Faux serveur unique : enregistre chaque requête reçue, répond par `repondre[service]`. */
export async function demarrerFaux() {
const journal = []
const repondre = fauxParDefaut()
const serveur = createServer(async (req, res) => {
const url = new URL(req.url, 'http://faux')
const [, service, ...reste] = url.pathname.split('/')
const { brut, json } = await lireCorps(req)
const entree = {
service,
methode: req.method,
chemin: '/' + reste.join('/'),
query: Object.fromEntries(url.searchParams),
entetes: req.headers,
brut,
json,
}
journal.push(entree)
const fn = repondre[service]
let r = fn ? await fn(entree) : { status: 404, json: { msg: `faux serveur : service inconnu « ${service} »` } }
if (r?.delaiMs) await new Promise((ok) => setTimeout(ok, r.delaiMs))
if (res.destroyed) return
res.writeHead(r?.status ?? 200, { 'Content-Type': 'application/json' })
res.end(r?.json !== undefined ? JSON.stringify(r.json) : (r?.texte ?? ''))
})
await new Promise((ok) => serveur.listen(0, '127.0.0.1', ok))
const url = `http://127.0.0.1:${serveur.address().port}`
return {
url,
journal,
repondre,
/** Requêtes reçues par un service (toutes si `service` absent). */
recu: (service) => (service ? journal.filter((e) => e.service === service) : journal.slice()),
/** Vide le journal et remet les réponses par défaut. */
reinitialiser() {
journal.length = 0
Object.assign(repondre, fauxParDefaut())
},
arreter: () => new Promise((ok) => { serveur.closeAllConnections?.(); serveur.close(() => ok()) }),
}
}
/** Bâtit l'application (`nuxt build`) sauf si BANC_SANS_BUILD=1 et qu'un `.output` existe. */
export function batir() {
const sortie = join(RACINE, '.output', 'server', 'index.mjs')
if (process.env.BANC_SANS_BUILD === '1' && existsSync(sortie)) {
console.log('[banc] BANC_SANS_BUILD=1 : build existant réutilisé')
return
}
console.log('[banc] nuxt build… (environ une minute)')
const t0 = Date.now()
const r = spawnSync('npx', ['nuxt', 'build'], { cwd: RACINE, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' })
if (r.status !== 0) {
console.error(r.stdout?.slice(-4000), r.stderr?.slice(-4000))
throw new Error('[banc] nuxt build a échoué')
}
console.log(`[banc] build fait en ${Math.round((Date.now() - t0) / 1000)} s`)
}
function portLibre() {
return new Promise((ok) => {
const s = createServer()
s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => ok(p)) })
})
}
/**
* Démarre le faux serveur puis l'application bâtie. `envSup` ajoute ou remplace des variables
* d'environnement de l'application.
*/
export async function demarrerBanc({ envSup = {}, build = true } = {}) {
if (build) batir()
const faux = await demarrerFaux()
const port = await portLibre()
const dossierLimites = mkdtempSync(join(tmpdir(), 'banc-limites-'))
const env = {
PATH: process.env.PATH,
NODE_ENV: 'production',
HOST: '127.0.0.1',
PORT: String(port),
NUXT_NOCODB_URL: `${faux.url}/nocodb`,
NUXT_NOCODB_TOKEN: 'faux',
NUXT_ORG_TABLE_ID: TABLES.orgs,
NUXT_STATS_TABLE_ID: TABLES.stats,
STATS_TABLE_ID: TABLES.stats,
NUXT_COMMENT_TABLE_ID: TABLES.comments,
NUXT_AVIS_TABLE_ID: TABLES.avis,
NUXT_BIFROST_URL: `${faux.url}/bifrost`,
NUXT_BIFROST_VK: 'faux',
NUXT_MISTRAL_API_KEY: 'faux',
MISTRAL_API_URL: `${faux.url}/mistral`,
RESEND_API_KEY: 'faux',
RESEND_API_URL: `${faux.url}/resend`,
NUXT_RESEND_API_KEY: 'faux',
EMAIL_JULES: 'jules@exemple.invalid',
NUXT_EMAIL_JULES: 'jules@exemple.invalid',
NUXT_RAG_PE_URL: `${faux.url}/rag`,
NUXT_RAG_EMANCIPATION_URL: `${faux.url}/rag-emancipation`,
NUXT_RAG_EMANCIPATION_KEY: 'faux',
NUXT_REDIS_URL: 'redis://127.0.0.1:1',
NAV_RATELIMIT_DIR: dossierLimites,
...envSup,
}
const appli = spawn(process.execPath, [join(RACINE, '.output', 'server', 'index.mjs')], { cwd: RACINE, env, stdio: ['ignore', 'pipe', 'pipe'] })
const journalAppli = []
appli.stdout.on('data', (d) => journalAppli.push(String(d)))
appli.stderr.on('data', (d) => journalAppli.push(String(d)))
const base = `http://127.0.0.1:${port}`
let pret = false
for (let i = 0; i < 100 && !pret; i++) {
if (appli.exitCode !== null) break
try { await fetch(`${base}/robots.txt`); pret = true } catch { await new Promise((ok) => setTimeout(ok, 100)) }
}
if (!pret) {
appli.kill('SIGKILL')
await faux.arreter()
throw new Error(`[banc] l'application n'a pas démarré :\n${journalAppli.join('')}`)
}
let ipSuivante = 1
return {
base,
faux,
tables: TABLES,
/** Journal (stdout + stderr) de l'application. */
journalAppli: () => journalAppli.join(''),
/** Une adresse de visiteur neuve à chaque appel (les limites de débit sont par adresse). */
ipNeuve: () => `10.${(ipSuivante >> 16) & 255}.${(ipSuivante >> 8) & 255}.${ipSuivante++ & 255}`,
/**
* Requête HTTP contre l'application. `json` : corps JSON ; `brut` : corps tel quel ;
* `ip` : valeur de X-Forwarded-For (sinon une adresse neuve). Rend { status, json, texte }.
*/
async requete(chemin, { method = 'GET', json, brut, ip, entetes = {} } = {}) {
const headers = { 'x-forwarded-for': ip ?? this.ipNeuve(), ...entetes }
let body
if (json !== undefined) { body = JSON.stringify(json); headers['content-type'] = 'application/json' }
if (brut !== undefined) { body = brut; headers['content-type'] ??= 'application/json' }
const res = await fetch(`${base}${chemin}`, { method, headers, body })
const texte = await res.text()
let j = null
try { j = JSON.parse(texte) } catch { /* HTML ou vide */ }
return { status: res.status, json: j, texte }
},
async arreter() {
if (appli.exitCode === null) {
appli.kill('SIGTERM')
await new Promise((ok) => { const t = setTimeout(() => { appli.kill('SIGKILL'); ok() }, 3000); appli.once('exit', () => { clearTimeout(t); ok() }) })
}
await faux.arreter()
rmSync(dossierLimites, { recursive: true, force: true })
},
}
}
/** Attend qu'une condition devienne vraie (écritures non attendues par la route, ex. stats_usage). */
export async function attendre(cond, { delaiMs = 3000, pasMs = 50 } = {}) {
const fin = Date.now() + delaiMs
while (Date.now() < fin) {
if (await cond()) return true
await new Promise((ok) => setTimeout(ok, pasMs))
}
return Boolean(await cond())
}
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env node
/**
* Banc de routes (lot SURFACE) : bâtit l'application une fois, la démarre sur un port local
* et joue des requêtes HTTP contre elle. Les services externes sont remplacés par le faux
* serveur de scripts/banc-routes.mjs, qui enregistre ce qu'il reçoit. Aucun appel réel.
*
* Usage : npm run test:routes (bâtit, ~1 min)
* BANC_SANS_BUILD=1 npm run test:routes (réutilise .output)
*/
import { demarrerBanc } from './banc-routes.mjs'
let ok = 0
let ko = 0
const echecs = []
function check(nom, cond, detail = '') {
if (cond) { ok++; console.log(` ✓ ${nom}`) }
else { ko++; echecs.push(nom); console.log(` ✗ ${nom}${detail ? ` — ${detail}` : ''}`) }
}
const banc = await demarrerBanc()
const { faux } = banc
async function groupe(titre, fn) {
console.log(`\n${titre}`)
faux.reinitialiser()
try { await fn() } catch (e) { ko++; echecs.push(`${titre} : exception`); console.log(` ✗ exception : ${e?.stack ?? e}`) }
}
try {
await groupe('A. Le banc joue les routes', async () => {
const r = await banc.requete('/robots.txt')
check('GET /robots.txt → 200', r.status === 200, `status ${r.status}`)
for (const chemin of ['/evenements/ruetz', '/evenements/ruetz/codev', '/evenements/ruetz/foret']) {
const p = await banc.requete(chemin)
check(`témoin Ruetz ${chemin} → 200`, p.status === 200, `status ${p.status}`)
}
const c = await banc.requete('/api/chatbot', { method: 'POST', json: { question: 'Qui fait de la paille à Lyon ?' } })
check('POST /api/chatbot nominal → 200', c.status === 200, `status ${c.status} ${c.texte.slice(0, 200)}`)
check('… la réponse vient du faux Bifrost', c.json?.reponse_texte === 'Réponse du faux modèle.')
check('… le faux Bifrost a reçu un appel', faux.recu('bifrost').length === 1)
const s = await banc.requete('/api/report', { method: 'POST', json: { fiche_id: 1, message: 'Le lien est mort.', email: 'a@b.fr' } })
check('POST /api/report nominal → 200', s.status === 200, `status ${s.status} ${s.texte.slice(0, 200)}`)
check('… le faux Resend a reçu le courriel', faux.recu('resend').length === 1)
const inconnus = faux.recu().filter((e) => !['nocodb', 'bifrost', 'mistral', 'resend', 'rag', 'rag-emancipation'].includes(e.service))
check('aucun appel vers un service non simulé', inconnus.length === 0, inconnus.map((e) => e.service).join(', '))
})
} finally {
await banc.arreter()
}
console.log(`\ntest-routes : ${ok} sur ${ok + ko}${ko ? ` — échecs : ${echecs.join(' · ')}` : ''}`)
process.exit(ko ? 1 : 0)