Files
courrier/tests/conftest.py
T

53 lines
1.8 KiB
Python

import os
import tempfile
import pytest
from fastapi.testclient import TestClient
import jwt
# Configuration impérative de l'environnement de test avant l'importation de l'application
TEST_SECRET = "secret-test-courrier-tt-2026-11-059"
os.environ["ENV"] = "test"
os.environ["CF_TEST_SECRET"] = TEST_SECRET
os.environ["CF_ACCESS_AUD"] = "courrier-test-aud"
from app.main import app
from app.db import init_db
@pytest.fixture
def temp_db():
"""Crée une base SQLite temporaire isolée pour chaque test."""
with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
db_path = f.name
init_db(db_path)
yield db_path
if os.path.exists(db_path):
os.remove(db_path)
@pytest.fixture
def valid_jwt_token():
"""Génère un jeton JWT valide pour les tests d'API."""
payload = {
"sub": "user@example.com",
"email": "user@example.com",
"aud": "courrier-test-aud",
"iss": "https://test.cloudflareaccess.com",
"exp": 9999999999
}
return jwt.encode(payload, TEST_SECRET, algorithm="HS256")
@pytest.fixture
def client(valid_jwt_token, temp_db, monkeypatch):
"""Client de test FastAPI avec injecteur d'en-tête Cloudflare Access et DB isolée."""
monkeypatch.setattr("app.config.DB_PATH", temp_db)
monkeypatch.setattr("app.db.DB_PATH", temp_db)
monkeypatch.setattr("app.config.ENV", "test")
monkeypatch.setattr("app.auth.ENV", "test")
monkeypatch.setattr("app.config.CF_TEST_SECRET", TEST_SECRET)
monkeypatch.setattr("app.auth.CF_TEST_SECRET", TEST_SECRET)
monkeypatch.setattr("app.config.CF_ACCESS_AUD", "courrier-test-aud")
monkeypatch.setattr("app.auth.CF_ACCESS_AUD", "courrier-test-aud")
init_db(temp_db)
with TestClient(app) as c:
c.headers.update({"Cf-Access-Jwt-Assertion": valid_jwt_token})
yield c