Compare commits

..

4 Commits

Author SHA1 Message Date
David
38a2e08062 fix preprod
Some checks failed
CD Preprod / Security gate (push) Successful in 29s
CD Preprod / Backend — Lint (push) Successful in 1m2s
CD Preprod / Backend — Unit Tests (push) Successful in 1m7s
CD Preprod / Frontend — Lint & Type-check (push) Successful in 1m11s
CD Preprod / Frontend — Unit Tests (push) Successful in 41s
CD Preprod / Backend — Integration Tests (push) Successful in 46s
CD Preprod / Build Frontend (push) Successful in 32s
CD Preprod / Build Backend (push) Successful in 53s
CD Preprod / Build Log Exporter (push) Successful in 32s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, frontend) (push) Successful in 23s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, backend) (push) Successful in 25s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, log-exporter) (push) Successful in 21s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, backend) (push) Successful in 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, frontend) (push) Successful in 23s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, log-exporter) (push) Successful in 22s
CD Preprod / Deploy to Preprod (push) Successful in 44s
CD Preprod / Notify Failure (push) Has been skipped
CD Preprod / Notify Success (push) Successful in 2s
Dev CI / Security gate (push) Failing after 1m35s
Dev CI / Backend — Lint (push) Successful in 1m56s
Dev CI / Frontend — Lint & Type-check (push) Successful in 1m16s
Dev CI / Frontend — Unit Tests (push) Successful in 48s
Dev CI / Backend — Unit Tests (push) Successful in 1m54s
Dev CI / Notify Failure (push) Has been skipped
2026-09-26 14:01:29 +02:00
David
b0aa23c0d4 fix
Some checks failed
CD Preprod / Security gate (push) Successful in 31s
CD Preprod / Backend — Lint (push) Successful in 1m4s
CD Preprod / Frontend — Lint & Type-check (push) Successful in 1m10s
CD Preprod / Backend — Unit Tests (push) Successful in 1m5s
CD Preprod / Frontend — Unit Tests (push) Successful in 43s
CD Preprod / Backend — Integration Tests (push) Successful in 46s
CD Preprod / Build Frontend (push) Successful in 33s
CD Preprod / Build Backend (push) Successful in 54s
CD Preprod / Build Log Exporter (push) Successful in 30s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, frontend) (push) Successful in 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, backend) (push) Successful in 25s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, log-exporter) (push) Successful in 22s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, backend) (push) Successful in 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, log-exporter) (push) Successful in 22s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, frontend) (push) Successful in 1m31s
CD Preprod / Deploy to Preprod (push) Failing after 42s
CD Preprod / Notify Success (push) Has been skipped
CD Preprod / Notify Failure (push) Has been skipped
2026-09-26 12:35:36 +02:00
David
450f1ffc18 fix
Some checks are pending
CD Preprod / Deploy to Preprod (push) Blocked by required conditions
CD Preprod / Notify Success (push) Blocked by required conditions
CD Preprod / Notify Failure (push) Blocked by required conditions
CD Preprod / Security gate (push) Successful in 29s
CD Preprod / Backend — Lint (push) Successful in 1m3s
CD Preprod / Frontend — Lint & Type-check (push) Successful in 1m9s
CD Preprod / Backend — Unit Tests (push) Successful in 1m5s
CD Preprod / Frontend — Unit Tests (push) Successful in 43s
CD Preprod / Backend — Integration Tests (push) Successful in 46s
CD Preprod / Build Frontend (push) Successful in 35s
CD Preprod / Build Backend (push) Successful in 1m3s
CD Preprod / Build Log Exporter (push) Successful in 34s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, backend) (push) Successful in 25s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, frontend) (push) Successful in 25s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, log-exporter) (push) Successful in 21s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, backend) (push) Successful in 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, frontend) (push) Successful in 23s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, log-exporter) (push) Successful in 22s
2026-09-25 16:59:38 +02:00
David
3434fa494d fix test
Some checks failed
CD Preprod / Security gate (push) Successful in 29s
CD Preprod / Backend — Lint (push) Successful in 1m5s
CD Preprod / Frontend — Lint & Type-check (push) Successful in 1m14s
CD Preprod / Backend — Unit Tests (push) Successful in 1m8s
CD Preprod / Frontend — Unit Tests (push) Successful in 43s
CD Preprod / Backend — Integration Tests (push) Successful in 46s
CD Preprod / Build Backend (push) Successful in 16m40s
CD Preprod / Build Log Exporter (push) Successful in 1m8s
CD Preprod / Build Frontend (push) Successful in 39m48s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, frontend) (push) Failing after 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, backend) (push) Failing after 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (amd64, log-exporter) (push) Failing after 22s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, backend) (push) Failing after 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, frontend) (push) Failing after 24s
CD Preprod / Image security (${{ matrix.service }}, ${{ matrix.arch }}) (arm64, log-exporter) (push) Failing after 21s
CD Preprod / Deploy to Preprod (push) Has been skipped
CD Preprod / Notify Success (push) Has been skipped
CD Preprod / Notify Failure (push) Has been skipped
2026-09-25 15:53:45 +02:00
14 changed files with 218 additions and 30 deletions

View File

@ -1,3 +1,2 @@
self-hosted-runner:
labels:
- xpeditis-deploy
# All jobs use the existing ubuntu-latest runner label.
{}

View File

@ -231,8 +231,11 @@ jobs:
PLATFORM: linux/${{ matrix.arch }}
run: |
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
--ignore-unfixed=false --exit-code 1 --timeout 15m --format json \
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
- name: Show image scan results
if: always()
run: python3 scripts/ci/summarize-image-security.py
- name: Save image report
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
@ -245,9 +248,8 @@ jobs:
# ═══ 4. Déploiement ══════════════════════════════════════════════════════
deploy:
name: Déployer en production
runs-on: xpeditis-deploy
runs-on: ubuntu-latest
needs: [verify-image, build-frontend, image-security]
# Gitea 1.22 ignores environments: serialize on the dedicated deployment runner.
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:

View File

@ -9,9 +9,10 @@ name: CD Preprod
# NEXT_PUBLIC_APP_URL — https://preprod.xpeditis.com
# PORTAINER_WEBHOOK_BACKEND — Portainer webhook (preprod backend)
# PORTAINER_WEBHOOK_FRONTEND— Portainer webhook (preprod frontend)
# PREPROD_BACKEND_URL — https://api.preprod.xpeditis.com
# PREPROD_FRONTEND_URL — https://preprod.xpeditis.com
# DISCORD_WEBHOOK_URL
# Optional health URL overrides (secrets, then repository variables):
# PREPROD_BACKEND_URL — defaults to https://api.preprod.xpeditis.com
# PREPROD_FRONTEND_URL — defaults to https://app.preprod.xpeditis.com
on:
push:
@ -312,8 +313,11 @@ jobs:
PLATFORM: linux/${{ matrix.arch }}
run: |
trivy image --platform "$PLATFORM" --scanners vuln --severity HIGH,CRITICAL \
--ignore-unfixed=false --exit-code 1 --timeout 15m --format json \
--ignore-unfixed=false --exit-code 1 --timeout 15m --no-progress --format json \
--output "$RUNNER_TEMP/image-security.json" "$IMAGE"
- name: Show image scan results
if: always()
run: python3 scripts/ci/summarize-image-security.py
- name: Save image report
if: always()
uses: https://github.com/actions/upload-artifact@ff15f0306b3f739f7b6fd43fb5d26cd321bd4de5 # v3, Gitea artifact protocol
@ -326,7 +330,7 @@ jobs:
# ── 5. Deploy via Portainer ──────────────────────────────────────────
deploy:
name: Deploy to Preprod
runs-on: xpeditis-deploy
runs-on: ubuntu-latest
needs: [build-backend, build-frontend, build-log-exporter, image-security]
steps:
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
@ -377,12 +381,12 @@ jobs:
- name: Verify backend health
env:
BASE_URL: ${{ secrets.PREPROD_BACKEND_URL }}
run: bash scripts/ci/health-check.sh "${BASE_URL:?Missing PREPROD_BACKEND_URL}/api/v1/health"
BASE_URL: ${{ secrets.PREPROD_BACKEND_URL || vars.PREPROD_BACKEND_URL || 'https://api.preprod.xpeditis.com' }}
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/v1/health"
- name: Verify frontend health
env:
BASE_URL: ${{ secrets.PREPROD_FRONTEND_URL }}
run: bash scripts/ci/health-check.sh "${BASE_URL:?Missing PREPROD_FRONTEND_URL}"
BASE_URL: ${{ secrets.PREPROD_FRONTEND_URL || vars.PREPROD_FRONTEND_URL || 'https://app.preprod.xpeditis.com' }}
run: bash scripts/ci/health-check.sh "${BASE_URL%/}/api/health"
- name: Mark successfully deployed preprod images
env:

View File

@ -40,6 +40,10 @@ RUN npm prune --production --legacy-peer-deps
# ===============================================
FROM node:22-alpine AS production
# Runtime starts with node; remove the base image package manager and its dependencies.
# npm remains available in the dependency and build stages.
RUN npm uninstall --global npm
# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init

View File

@ -1,6 +1,6 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import request from 'supertest';
import { AppModule } from '../src/app.module';
describe('AppController (e2e)', () => {

View File

@ -0,0 +1,45 @@
import { randomUUID } from 'crypto';
import { ConfigService } from '@nestjs/config';
import { RedisCacheAdapter } from '../../src/infrastructure/cache/redis-cache.adapter';
describe('Redis cache integration', () => {
let cache: RedisCacheAdapter;
const prefix = `integration:${randomUUID()}:`;
const keys = ['value', 'expires'].map(key => `${prefix}${key}`);
beforeAll(async () => {
cache = new RedisCacheAdapter(
new ConfigService({
REDIS_HOST: process.env.REDIS_HOST,
REDIS_PORT: Number(process.env.REDIS_PORT),
REDIS_PASSWORD: process.env.REDIS_PASSWORD || undefined,
REDIS_DB: Number(process.env.REDIS_DB),
})
);
await cache.onModuleInit();
});
afterAll(async () => {
try {
// Delete only this suite's keys; never flush a shared database.
await cache.deleteMany(keys);
} finally {
await cache.onModuleDestroy();
}
});
it('round-trips cached application data and invalidates it', async () => {
const value = { amount: 125.5, currency: 'EUR', ports: ['FRLEH', 'USNYC'] };
await cache.set(keys[0], value, 60);
expect(await cache.get(keys[0])).toEqual(value);
await cache.delete(keys[0]);
expect(await cache.get(keys[0])).toBeNull();
});
it('expires cached data using the server TTL', async () => {
await cache.set(keys[1], { valid: true }, 1);
expect(await cache.exists(keys[1])).toBe(true);
await new Promise(resolve => setTimeout(resolve, 1200));
expect(await cache.exists(keys[1])).toBe(false);
});
});

View File

@ -1,7 +1,10 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "../",
"testMatch": ["**/test/integration/**/*.spec.ts"],
"testMatch": [
"<rootDir>/test/integration/**/*.spec.ts",
"<rootDir>/src/infrastructure/persistence/typeorm/repositories/typeorm-trade-quota.repository.spec.ts"
],
"transform": {
"^.+\\.(t|j)s$": [
"ts-jest",
@ -19,7 +22,7 @@
"testEnvironment": "node",
"moduleNameMapper": {
"^@domain/(.*)$": "<rootDir>/src/domain/$1",
"@application/(.*)$": "<rootDir>/src/application/$1",
"^@application/(.*)$": "<rootDir>/src/application/$1",
"^@infrastructure/(.*)$": "<rootDir>/src/infrastructure/$1"
},
"transformIgnorePatterns": ["node_modules/(?!(@faker-js)/)"],

View File

@ -11,6 +11,18 @@ process.env.TEST_DB_USER = process.env.TEST_DB_USER || 'postgres';
process.env.TEST_DB_PASSWORD = process.env.TEST_DB_PASSWORD || 'postgres';
process.env.TEST_DB_NAME = process.env.TEST_DB_NAME || 'xpeditis_test';
// Enable the repository integration suite using the disposable CI service.
// Never fall back to DATABASE_* (the application's deployment connection).
if (!process.env.TRADE_TEST_DATABASE_URL) {
const database = new URL('postgresql://localhost');
database.hostname = process.env.TEST_DB_HOST;
database.port = process.env.TEST_DB_PORT;
database.username = process.env.TEST_DB_USER;
database.password = process.env.TEST_DB_PASSWORD;
database.pathname = `/${process.env.TEST_DB_NAME}`;
process.env.TRADE_TEST_DATABASE_URL = database.toString();
}
// Redis test configuration
process.env.REDIS_HOST = process.env.REDIS_HOST || 'localhost';
process.env.REDIS_PORT = process.env.REDIS_PORT || '6379';

View File

@ -50,6 +50,10 @@ RUN npm run build
# ===============================================
FROM node:22-alpine AS production
# Runtime starts with node; remove the base image package manager and its dependencies.
# npm remains available in the dependency and build stages.
RUN npm uninstall --global npm
# Install dumb-init for proper signal handling
RUN apk add --no-cache dumb-init curl

View File

@ -5,6 +5,9 @@ WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
# Only Node and application dependencies are needed at runtime.
RUN npm uninstall --global npm
COPY src/ ./src/
EXPOSE 3200

View File

@ -80,21 +80,31 @@ comme des protections effectives dans les workflows adaptés.
Docker. Les builds multiarchitecture ont besoin du support QEMU/binfmt.
Les services d'intégration sont joints via `postgres` et `redis`, sans ports
hôte fixes ; un runner en mode host n'est pas la cible de ces workflows.
2. Enregistrer **un seul runner** avec le label **`xpeditis-deploy`**, une capacité
**1**, et une limite d'exécution adaptée (par exemple 1 h). Les deux jobs de
déploiement utilisent ce label : publication des alias, déploiement, santé et
fermeture du firewall restent dans le même job. Ne pas donner ce label à
plusieurs runners. Le runner doit être isolé des jobs de PR et disposer de
Docker, Git, curl, SSH et rsync. Sans ce runner, les déploiements restent en attente.
2. Les déploiements préprod et production utilisent le runner existant avec le
label **`ubuntu-latest`**, comme les builds et les audits. Aucun runner dédié
`xpeditis-deploy` n'est nécessaire. Ce runner doit aussi disposer de SSH et
rsync pour le déploiement de production. Gitea 1.22 ne prenant pas en charge
`concurrency`, les workflows ne garantissent pas la sérialisation des
déploiements si les runners autorisent plusieurs jobs simultanés.
Pour éviter les chevauchements, attendre la fin d'un déploiement avant de
déclencher le suivant sur le même environnement.
3. Protéger `dev`, `preprod`, `main` dans les réglages de branches Gitea : interdire
les push directs/force-push et exiger **Security gate**, les deux contrôles
qualité et les deux tests unitaires ; ajouter l'intégration pour preprod/main.
Choisir les noms exacts proposés après la première exécution. Les approbations
humaines doivent être imposées sur les PR, pas via `environment`.
4. Renseigner les secrets/variables dans **Settings → Actions** du dépôt Gitea :
registre, webhooks Portainer, URLs préprod, URLs de build et identifiants
registre, webhooks Portainer, URLs de build et identifiants
SSH/Hetzner déjà référencés. Les secrets ne sont pas des secrets d'environnement
GitHub. Les clés SSH temporaires sont écrites dans le répertoire du job.
Les contrôles de santé préprod utilisent par défaut
`https://api.preprod.xpeditis.com/api/v1/health` et
`https://app.preprod.xpeditis.com/api/health`, conformément aux routes Traefik
de la stack. Le contrôle frontend cible son endpoint de santé pour éviter
la redirection HTTP 307 de la page d’accueil.
`PREPROD_BACKEND_URL` et `PREPROD_FRONTEND_URL` sont des surcharges facultatives
(URL de base sans chemin API), lues dans les secrets puis les variables du dépôt.
Une réponse HTTP 200 reste obligatoire pour valider le déploiement.
5. Les fonctions manuelles `workflow_dispatch` ne sont pas disponibles sur 1.22.
L'ancien workflow de rollback est conservé hors du dossier actif dans
`.gitea/manual/rollback.reference.yml` comme référence, sans prétendre qu'il est
@ -234,3 +244,34 @@ exécution Gitea n'est effectué par cette correction locale.
Sources : [migration Next 15](https://nextjs.org/docs/app/guides/upgrading/version-15),
[distribution SheetJS](https://docs.sheetjs.com/docs/getting-started/installation/nodejs/),
[exceptions Trivy](https://trivy.dev/docs/dev/configuration/filtering/).
## Images de déploiement : npm global (25 septembre 2026)
Les rapports du run Gitea 150 attribuent huit alertes HIGH identiques, sur AMD64
et ARM64, aux dépendances du npm global livré dans `node:22-alpine` :
`usr/local/lib/node_modules/npm/node_modules/...`. Les audits npm du projet ne
couvrent pas ce gestionnaire global ; un audit applicatif vert ne suffit donc
pas à valider l'image finale.
Les trois Dockerfiles désinstallent le npm global avec `npm uninstall --global
npm` uniquement après les installations nécessaires, dans l'image d'exécution.
Le backend et le frontend gardent npm dans leurs étages de construction.
Les services démarrent avec Node, et les migrations backend utilisent directement
TypeORM via `startup.js`. La procédure manuelle Portainer utilise également Node.
Aucune CVE n'est ignorée et les scans par digest restent bloquants en préprod/prod.
Chaque job de scan affiche maintenant un résumé indiquant CVE, paquet, version,
correctif disponible et chemin, même après échec. Le rapport JSON complet reste
joint en artefact. Les barres de progression sont désactivées pour éviter les
journaux illisibles. L'avertissement de Trivy 0.74 sur la liste EOL d'Alpine 3.24
n'est pas la cause du code de sortie 1 observé : il est aussi présent sur les
scans corrigés qui retournent 0.
Validation du correctif : reconstruction des trois images ARM64 et du log-exporter
AMD64 ; scans Trivy au seuil HIGH/CRITICAL sans exclusions ; HTTP 200 sur les
routes de santé frontend et log-exporter ; chargement du démarrage backend et de
la CLI TypeORM sans npm/npx ; validation des workflows et 30 tests de scripts.
Les images backend/frontend AMD64 et le déploiement restent à confirmer par la
prochaine exécution Gitea après publication du correctif. Relancer uniquement les
anciens jobs de scan réanalyse les anciens digests vulnérables : il faut rebâtir
les images à partir du commit corrigé.

View File

@ -144,12 +144,12 @@ NEXT_PUBLIC_API_URL=https://api.xpeditis.com
## Migrations automatiques
Le backend exécute les migrations automatiquement au démarrage via le script `docker-entrypoint.sh` :
Le backend exécute les migrations automatiquement via `startup.js`, qui attend PostgreSQL,
appelle directement TypeORM puis lance le serveur Node. npm n’est pas présent dans l’image finale :
```bash
# apps/backend/docker-entrypoint.sh attend PostgreSQL puis :
npm run migration:run
node dist/main.js
# Commande de démarrage de l’image
node startup.js
```
Les logs Portainer affichent :
@ -199,8 +199,7 @@ traefik.http.services.frontend.loadbalancer.server.port=3000
### Migrations échouent
```bash
docker exec -it xpeditis-backend sh
cd /app && npm run migration:run
docker exec -it xpeditis-backend node -e 'require("./startup").runMigrations().catch(() => process.exit(1))'
```
Si blocage : vérifier que PostgreSQL est accessible (`DATABASE_HOST` = nom du service Docker).

View File

@ -0,0 +1,32 @@
"""Show actionable image findings even when the blocking Trivy step failed."""
import json
import os
from pathlib import Path
def summarize(path):
try:
report = json.loads(path.read_text())
if not isinstance(report, dict) or not isinstance(report.get('Results'), list):
raise ValueError('Missing scan results')
except (OSError, ValueError):
print('Image report missing or invalid: inspect the Trivy step; scan not verified.')
return 1
count = 0
for result in report['Results']:
for finding in result.get('Vulnerabilities') or []:
if finding.get('Severity') not in ('HIGH', 'CRITICAL'):
continue
count += 1
print(f'{finding["Severity"]} {finding.get("VulnerabilityID", "unknown")}: '
f'{finding.get("PkgName", "unknown")} '
f'{finding.get("InstalledVersion", "unknown")} -> '
f'{finding.get("FixedVersion") or "no fixed version published"}')
print(f' Path: {finding.get("PkgPath") or result.get("Target", "unknown")}')
print(f'{count} HIGH/CRITICAL image findings. Full details: image-security artifact.')
return int(count > 0)
if __name__ == '__main__':
raise SystemExit(summarize(Path(os.environ['RUNNER_TEMP']) / 'image-security.json'))

View File

@ -0,0 +1,40 @@
import contextlib
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location(
'image_summary', Path(__file__).with_name('summarize-image-security.py'))
summary = importlib.util.module_from_spec(spec)
spec.loader.exec_module(summary)
class ImageSummary(unittest.TestCase):
def test_reports_global_npm_path_and_preserves_failure(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'image-security.json'
path.write_text(json.dumps({'Results': [{'Vulnerabilities': [{
'Severity': 'HIGH', 'VulnerabilityID': 'CVE-example',
'PkgName': 'pacote', 'InstalledVersion': '19.0.2',
'FixedVersion': '21.5.1',
'PkgPath': 'usr/local/lib/node_modules/npm/node_modules/pacote/package.json',
}]}]}))
output = io.StringIO()
with contextlib.redirect_stdout(output):
self.assertEqual(summary.summarize(path), 1)
self.assertIn('19.0.2 -> 21.5.1', output.getvalue())
self.assertIn('usr/local/lib/node_modules/npm/', output.getvalue())
def test_missing_invalid_and_clean_reports(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'image-security.json'
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(summary.summarize(path), 1)
for content in ('broken', '{}', '{"Results": null}'):
path.write_text(content)
self.assertEqual(summary.summarize(path), 1)
path.write_text('{"Results": []}')
self.assertEqual(summary.summarize(path), 0)