Spaces:
Runtime error
fix(chunker,personas): perte de contenu sur faux en-tete, engagement en 500
Browse filestext_chunker : le motif de section etait compile avec re.IGNORECASE. Un article
dont le titre commence par "Titre 1" ou "Chapitre 2" etait donc pris pour un
en-tete de section — et le decoupeur coupe tout ce qui suit un en-tete trouve
dans un article. L'article perdait la totalite de son texte, sans erreur, juste
un "trop court (0 chars), ignore" en journal. Detection desormais sensible a la
casse : les en-tetes du corpus sont en capitales. Le compromis est asymetrique,
rater un en-tete en minuscules coute une metadonnee, le confondre avec un titre
coute l'article.
persona_service.get_engagement_metrics : la sortie anticipee "aucune
conversation" omettait conversations_per_active_day, champ obligatoire du
schema. GET /personas/{p}/engagement renvoyait donc 500 pour tout persona sans
conversation sur la periode — soit tous, sur une base neuve.
Tests remis en phase avec le code :
- extraction : la regle "minimum 3 articles" a ete retiree du chunker et ne doit
pas revenir, la majorite du corpus etant des decrets de nomination a deux
articles ; le premier chunk porte desormais le preambule, l'extraction ne
jetant plus aucun caractere.
- law_service : nom et nombre de categories lus depuis le seed au lieu d'etre
figes ("Droit civil" contre "Droit Civil", 3 contre 12).
- language_detector : spaCy a ete retire du service, le health check ne declare
plus que fastText.
- rag_routes : la doublure visait service.ollama, nom disparu ; l'AsyncMock nu
laissait une coroutine dans la reponse.
- full_pipeline : appelait detect_language (methode inexistante, c'est detect),
indexait la sortie de classify comme un dictionnaire et attendait des
embeddings 768-dim (3072 avec Gemini). Repare, et desormais derriere
JURIX_E2E=1 : ces deux tests appellent Gemini pour de vrai.
Suite complete : 472 passants, 14 ignores, 0 echec (26 echecs au depart).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
- app/services/persona_service.py +6 -1
- app/utils/text_chunker.py +11 -2
- tests/test_api/test_rag_routes.py +9 -4
- tests/test_integration/test_article_extraction_integration.py +33 -11
- tests/test_integration/test_full_pipeline.py +27 -9
- tests/test_services/test_language_detector.py +6 -6
- tests/test_services/test_law_service.py +13 -3
|
@@ -869,7 +869,12 @@ class PersonaService:
|
|
| 869 |
"total_messages": 0,
|
| 870 |
"avg_messages_per_conversation": 0.0,
|
| 871 |
"avg_session_duration_seconds": 0,
|
| 872 |
-
"active_days": 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 873 |
}
|
| 874 |
}
|
| 875 |
|
|
|
|
| 869 |
"total_messages": 0,
|
| 870 |
"avg_messages_per_conversation": 0.0,
|
| 871 |
"avg_session_duration_seconds": 0,
|
| 872 |
+
"active_days": 0,
|
| 873 |
+
# Champ obligatoire de DetailedEngagementMetrics. Absent, la
|
| 874 |
+
# reponse ne se serialisait pas et l'endpoint renvoyait 500
|
| 875 |
+
# des qu'un persona n'avait aucune conversation sur la
|
| 876 |
+
# periode — c'est-a-dire toujours sur une base neuve.
|
| 877 |
+
"conversations_per_active_day": 0.0
|
| 878 |
}
|
| 879 |
}
|
| 880 |
|
|
@@ -567,10 +567,19 @@ def _split_by_pattern_with_sections(text: str, pattern: re.Pattern) -> List[Tupl
|
|
| 567 |
"""
|
| 568 |
articles = []
|
| 569 |
|
| 570 |
-
# Compile section patterns
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
section_pattern = re.compile(
|
| 572 |
'|'.join(f'({p})' for p in SECTION_PATTERNS),
|
| 573 |
-
re.
|
| 574 |
)
|
| 575 |
|
| 576 |
# Find all article matches
|
|
|
|
| 567 |
"""
|
| 568 |
articles = []
|
| 569 |
|
| 570 |
+
# Compile section patterns.
|
| 571 |
+
# SANS re.IGNORECASE : le mot-cle doit etre en capitales, comme dans les
|
| 572 |
+
# textes du corpus ("CHAPITRE I - DISPOSITIONS GENERALES"). Avec
|
| 573 |
+
# IGNORECASE, un titre d'article commencant par "Titre 1" ou "Chapitre 2"
|
| 574 |
+
# etait pris pour un en-tete de section — et plus bas, tout le contenu qui
|
| 575 |
+
# suit un en-tete trouve DANS un article est coupe. Un article dont le
|
| 576 |
+
# titre ressemblait a une section perdait donc la totalite de son texte,
|
| 577 |
+
# silencieusement. Le compromis est asymetrique : rater un en-tete en
|
| 578 |
+
# minuscules ne coute qu'une metadonnee de section, le confondre avec un
|
| 579 |
+
# titre coute l'article entier.
|
| 580 |
section_pattern = re.compile(
|
| 581 |
'|'.join(f'({p})' for p in SECTION_PATTERNS),
|
| 582 |
+
re.MULTILINE
|
| 583 |
)
|
| 584 |
|
| 585 |
# Find all article matches
|
|
@@ -235,11 +235,15 @@ class TestHealthEndpoint:
|
|
| 235 |
def test_health_check(self, mock_rag_service_class, client):
|
| 236 |
"""Test health check endpoint."""
|
| 237 |
# Mock healthy service
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
mock_service = AsyncMock()
|
| 239 |
-
mock_service.
|
| 240 |
-
mock_service.
|
| 241 |
"status": "healthy",
|
| 242 |
-
"model": "
|
| 243 |
"available": True
|
| 244 |
})
|
| 245 |
mock_service.db = AsyncMock()
|
|
@@ -253,6 +257,7 @@ class TestHealthEndpoint:
|
|
| 253 |
assert response.status_code == 200
|
| 254 |
data = response.json()
|
| 255 |
assert "status" in data
|
| 256 |
-
assert "
|
|
|
|
| 257 |
assert "database" in data
|
| 258 |
assert "search_service" in data
|
|
|
|
| 235 |
def test_health_check(self, mock_rag_service_class, client):
|
| 236 |
"""Test health check endpoint."""
|
| 237 |
# Mock healthy service
|
| 238 |
+
# L'attribut est llm (GeminiService), plus ollama : la doublure posee
|
| 239 |
+
# sur un nom disparu laissait un AsyncMock nu sur llm, dont .get()
|
| 240 |
+
# renvoyait une coroutine placee telle quelle dans la reponse
|
| 241 |
+
# ("Unable to serialize unknown type: <class 'coroutine'>").
|
| 242 |
mock_service = AsyncMock()
|
| 243 |
+
mock_service.llm = AsyncMock()
|
| 244 |
+
mock_service.llm.health_check = AsyncMock(return_value={
|
| 245 |
"status": "healthy",
|
| 246 |
+
"model": "gemini-2.0-flash",
|
| 247 |
"available": True
|
| 248 |
})
|
| 249 |
mock_service.db = AsyncMock()
|
|
|
|
| 257 |
assert response.status_code == 200
|
| 258 |
data = response.json()
|
| 259 |
assert "status" in data
|
| 260 |
+
assert "llm" in data
|
| 261 |
+
assert data["llm"] == "healthy"
|
| 262 |
assert "database" in data
|
| 263 |
assert "search_service" in data
|
|
@@ -6,7 +6,7 @@ as intended in the process_law task.
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import pytest
|
| 9 |
-
from app.utils.text_chunker import extract_articles
|
| 10 |
|
| 11 |
|
| 12 |
class TestArticleExtractionIntegration:
|
|
@@ -44,20 +44,31 @@ class TestArticleExtractionIntegration:
|
|
| 44 |
en fonction de la forme juridique et du secteur d'activité concerné.
|
| 45 |
"""
|
| 46 |
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
# Verify extraction
|
| 50 |
assert len(articles) == 5
|
| 51 |
-
assert
|
| 52 |
|
| 53 |
# Verify structure
|
| 54 |
-
assert articles[0]['number'] == '1'
|
| 55 |
assert articles[0]['title'] == 'Objet de la loi'
|
| 56 |
assert 'OHADA' in articles[0]['content']
|
| 57 |
|
| 58 |
assert articles[3]['number'] == '4'
|
| 59 |
assert articles[3]['title'] == 'Conditions de constitution'
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
# Verify all have required fields
|
| 62 |
for article in articles:
|
| 63 |
assert 'number' in article
|
|
@@ -68,19 +79,30 @@ class TestArticleExtractionIntegration:
|
|
| 68 |
assert article['word_count'] > 0
|
| 69 |
assert article['char_count'] > 0
|
| 70 |
|
| 71 |
-
def
|
| 72 |
-
"""
|
| 73 |
-
|
| 74 |
Article 1. Premier article
|
| 75 |
Contenu du premier article avec suffisamment de texte pour validation.
|
| 76 |
|
| 77 |
Article 2. Deuxième article seulement
|
| 78 |
-
Contenu du deuxième article, mais
|
| 79 |
"""
|
| 80 |
|
| 81 |
-
#
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def test_pipeline_processes_large_document(self):
|
| 86 |
"""Test that pipeline can handle large legal documents."""
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import pytest
|
| 9 |
+
from app.utils.text_chunker import extract_articles
|
| 10 |
|
| 11 |
|
| 12 |
class TestArticleExtractionIntegration:
|
|
|
|
| 44 |
en fonction de la forme juridique et du secteur d'activité concerné.
|
| 45 |
"""
|
| 46 |
|
| 47 |
+
chunks = extract_articles(law_text)
|
| 48 |
+
|
| 49 |
+
# Le premier chunk porte l'en-tete du texte (intitule de la loi), sous
|
| 50 |
+
# le numero PREAMBULE ou LEGAL_BASIS : l'extraction ne jette aucun
|
| 51 |
+
# caractere du document. Les articles proprement dits sont donc filtres.
|
| 52 |
+
assert chunks[0]['number'] in ('PREAMBULE', 'LEGAL_BASIS')
|
| 53 |
+
assert 'LOI N° 2023-001' in chunks[0]['content']
|
| 54 |
+
|
| 55 |
+
articles = [c for c in chunks if c['number'].isdigit()]
|
| 56 |
|
| 57 |
# Verify extraction
|
| 58 |
assert len(articles) == 5
|
| 59 |
+
assert [a['number'] for a in articles] == ['1', '2', '3', '4', '5']
|
| 60 |
|
| 61 |
# Verify structure
|
|
|
|
| 62 |
assert articles[0]['title'] == 'Objet de la loi'
|
| 63 |
assert 'OHADA' in articles[0]['content']
|
| 64 |
|
| 65 |
assert articles[3]['number'] == '4'
|
| 66 |
assert articles[3]['title'] == 'Conditions de constitution'
|
| 67 |
|
| 68 |
+
# La section est rattachee a chaque article
|
| 69 |
+
assert articles[0]['section'].startswith('CHAPITRE I')
|
| 70 |
+
assert articles[3]['section'].startswith('CHAPITRE II')
|
| 71 |
+
|
| 72 |
# Verify all have required fields
|
| 73 |
for article in articles:
|
| 74 |
assert 'number' in article
|
|
|
|
| 79 |
assert article['word_count'] > 0
|
| 80 |
assert article['char_count'] > 0
|
| 81 |
|
| 82 |
+
def test_short_document_is_extracted(self):
|
| 83 |
+
"""Un texte de deux articles est extrait, pas rejete."""
|
| 84 |
+
short_text = """
|
| 85 |
Article 1. Premier article
|
| 86 |
Contenu du premier article avec suffisamment de texte pour validation.
|
| 87 |
|
| 88 |
Article 2. Deuxième article seulement
|
| 89 |
+
Contenu du deuxième article, court mais parfaitement valide.
|
| 90 |
"""
|
| 91 |
|
| 92 |
+
# L'ancienne regle "minimum 3 articles" a ete retiree du chunker, et
|
| 93 |
+
# elle ne doit pas revenir : la majorite du corpus est faite de decrets
|
| 94 |
+
# de nomination a deux articles ("Article 1er : est nomme... / Article
|
| 95 |
+
# 2 : le present decret sera enregistre..."). La retablir refuserait
|
| 96 |
+
# l'essentiel des documents.
|
| 97 |
+
articles = extract_articles(short_text)
|
| 98 |
+
|
| 99 |
+
assert [a['number'] for a in articles] == ['1', '2']
|
| 100 |
+
assert all(a['char_count'] > 0 for a in articles)
|
| 101 |
+
|
| 102 |
+
def test_empty_document_raises(self):
|
| 103 |
+
"""Un document sans contenu exploitable leve toujours."""
|
| 104 |
+
with pytest.raises(ValueError):
|
| 105 |
+
extract_articles(" \n \n ")
|
| 106 |
|
| 107 |
def test_pipeline_processes_large_document(self):
|
| 108 |
"""Test that pipeline can handle large legal documents."""
|
|
@@ -17,6 +17,8 @@ Author: JuriX Team
|
|
| 17 |
Date: 2026-01-10
|
| 18 |
"""
|
| 19 |
|
|
|
|
|
|
|
| 20 |
import pytest
|
| 21 |
from datetime import date
|
| 22 |
import time
|
|
@@ -33,6 +35,17 @@ from app.schemas.search import SearchRequest
|
|
| 33 |
from app.schemas.rag import RAGRequest
|
| 34 |
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
@pytest.fixture
|
| 37 |
def sample_legal_document():
|
| 38 |
"""Sample Cameroonian legal document."""
|
|
@@ -89,17 +102,21 @@ async def test_full_pipeline_integration(
|
|
| 89 |
|
| 90 |
# STEP 1: Language Detection
|
| 91 |
print("\n1️⃣ Testing Language Detection...")
|
| 92 |
-
lang_result = language_detector.
|
| 93 |
assert lang_result["language"] == "fr"
|
| 94 |
assert lang_result["confidence"] > 0.9
|
| 95 |
print(f" ✅ Detected language: {lang_result['language']} ({lang_result['confidence']:.2%})")
|
| 96 |
|
| 97 |
# STEP 2: Document Classification
|
| 98 |
print("\n2️⃣ Testing Document Classification...")
|
|
|
|
|
|
|
| 99 |
class_result = document_classifier.classify(sample_legal_document, top_k=3)
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
|
|
|
|
|
|
| 103 |
|
| 104 |
# STEP 3: Article Extraction
|
| 105 |
print("\n3️⃣ Testing Article Extraction...")
|
|
@@ -145,9 +162,10 @@ async def test_full_pipeline_integration(
|
|
| 145 |
embeddings = embedding_service.generate_batch_embeddings([
|
| 146 |
article["content"] for article in articles[:5]
|
| 147 |
])
|
|
|
|
| 148 |
assert len(embeddings) == min(5, len(articles))
|
| 149 |
-
assert all(emb.shape == (
|
| 150 |
-
print(f" ✅ Generated {len(embeddings)} embeddings (
|
| 151 |
|
| 152 |
# STEP 7: Hybrid Search
|
| 153 |
print("\n7️⃣ Testing Hybrid Search...")
|
|
@@ -177,8 +195,8 @@ async def test_full_pipeline_integration(
|
|
| 177 |
print(f" Confidence: {rag_response.confidence:.2%}")
|
| 178 |
print(f" Sources: {len(rag_response.sources)}")
|
| 179 |
except Exception as e:
|
| 180 |
-
print(f" ⚠️ RAG test skipped (
|
| 181 |
-
pytest.skip("
|
| 182 |
|
| 183 |
# Cleanup
|
| 184 |
print("\n9️⃣ Cleanup...")
|
|
@@ -211,7 +229,7 @@ async def test_pipeline_performance(sample_legal_document, async_db_session):
|
|
| 211 |
# Language Detection
|
| 212 |
language_detector = LanguageDetector()
|
| 213 |
start = time.time()
|
| 214 |
-
lang_result = language_detector.
|
| 215 |
timings["language_detection"] = (time.time() - start) * 1000
|
| 216 |
assert timings["language_detection"] < 1000 # <1s
|
| 217 |
print(f"✅ Language Detection: {timings['language_detection']:.0f}ms (target: <1000ms)")
|
|
|
|
| 17 |
Date: 2026-01-10
|
| 18 |
"""
|
| 19 |
|
| 20 |
+
import os
|
| 21 |
+
|
| 22 |
import pytest
|
| 23 |
from datetime import date
|
| 24 |
import time
|
|
|
|
| 35 |
from app.schemas.rag import RAGRequest
|
| 36 |
|
| 37 |
|
| 38 |
+
# Ces deux tests appellent l'API Gemini pour de vrai (embeddings puis RAG) :
|
| 39 |
+
# ils consomment du quota et dependent du reseau. Ils ne s'executent donc que
|
| 40 |
+
# sur demande explicite, JURIX_E2E=1, et jamais dans la suite ordinaire.
|
| 41 |
+
# Chaque etage a par ailleurs sa propre suite unitaire ; ce fichier ne verifie
|
| 42 |
+
# que leur enchainement.
|
| 43 |
+
pytestmark = pytest.mark.skipif(
|
| 44 |
+
os.getenv("JURIX_E2E") != "1",
|
| 45 |
+
reason="Chaine complete avec appels Gemini reels : lancer avec JURIX_E2E=1",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
@pytest.fixture
|
| 50 |
def sample_legal_document():
|
| 51 |
"""Sample Cameroonian legal document."""
|
|
|
|
| 102 |
|
| 103 |
# STEP 1: Language Detection
|
| 104 |
print("\n1️⃣ Testing Language Detection...")
|
| 105 |
+
lang_result = language_detector.detect(sample_legal_document)
|
| 106 |
assert lang_result["language"] == "fr"
|
| 107 |
assert lang_result["confidence"] > 0.9
|
| 108 |
print(f" ✅ Detected language: {lang_result['language']} ({lang_result['confidence']:.2%})")
|
| 109 |
|
| 110 |
# STEP 2: Document Classification
|
| 111 |
print("\n2️⃣ Testing Document Classification...")
|
| 112 |
+
# classify renvoie une liste de tuples (category_id, confidence, method),
|
| 113 |
+
# pas un dictionnaire {"predictions": [...]}.
|
| 114 |
class_result = document_classifier.classify(sample_legal_document, top_k=3)
|
| 115 |
+
assert 1 <= len(class_result) <= 3
|
| 116 |
+
top_category_id, top_confidence, top_method = class_result[0]
|
| 117 |
+
assert isinstance(top_category_id, int) and top_category_id > 0
|
| 118 |
+
assert 0.0 <= top_confidence <= 1.0
|
| 119 |
+
print(f" ✅ Classified as: category {top_category_id} ({top_confidence:.2%}, {top_method})")
|
| 120 |
|
| 121 |
# STEP 3: Article Extraction
|
| 122 |
print("\n3️⃣ Testing Article Extraction...")
|
|
|
|
| 162 |
embeddings = embedding_service.generate_batch_embeddings([
|
| 163 |
article["content"] for article in articles[:5]
|
| 164 |
])
|
| 165 |
+
dim = EmbeddingService.EMBEDDING_DIM # 3072 avec Gemini, plus 768
|
| 166 |
assert len(embeddings) == min(5, len(articles))
|
| 167 |
+
assert all(emb.shape == (dim,) for emb in embeddings)
|
| 168 |
+
print(f" ✅ Generated {len(embeddings)} embeddings ({dim}-dim)")
|
| 169 |
|
| 170 |
# STEP 7: Hybrid Search
|
| 171 |
print("\n7️⃣ Testing Hybrid Search...")
|
|
|
|
| 195 |
print(f" Confidence: {rag_response.confidence:.2%}")
|
| 196 |
print(f" Sources: {len(rag_response.sources)}")
|
| 197 |
except Exception as e:
|
| 198 |
+
print(f" ⚠️ RAG test skipped (Gemini indisponible): {e}")
|
| 199 |
+
pytest.skip("Service Gemini indisponible")
|
| 200 |
|
| 201 |
# Cleanup
|
| 202 |
print("\n9️⃣ Cleanup...")
|
|
|
|
| 229 |
# Language Detection
|
| 230 |
language_detector = LanguageDetector()
|
| 231 |
start = time.time()
|
| 232 |
+
lang_result = language_detector.detect(sample_legal_document)
|
| 233 |
timings["language_detection"] = (time.time() - start) * 1000
|
| 234 |
assert timings["language_detection"] < 1000 # <1s
|
| 235 |
print(f"✅ Language Detection: {timings['language_detection']:.0f}ms (target: <1000ms)")
|
|
@@ -265,15 +265,15 @@ class TestLanguageDetectorHealthCheck:
|
|
| 265 |
|
| 266 |
models = health["models"]
|
| 267 |
|
| 268 |
-
#
|
| 269 |
-
|
| 270 |
-
|
| 271 |
assert "fasttext" in models
|
|
|
|
|
|
|
| 272 |
|
| 273 |
-
# Si service healthy,
|
| 274 |
if health["status"] == "healthy":
|
| 275 |
-
assert "✅" in models["spacy_fr"]
|
| 276 |
-
assert "✅" in models["spacy_en"]
|
| 277 |
assert "✅" in models["fasttext"]
|
| 278 |
|
| 279 |
|
|
|
|
| 265 |
|
| 266 |
models = health["models"]
|
| 267 |
|
| 268 |
+
# fastText est le seul modele restant : spaCy a ete retire du service
|
| 269 |
+
# (les deux modeles spacy_fr / spacy_en n'etaient plus charges ni
|
| 270 |
+
# declares dans les dependances).
|
| 271 |
assert "fasttext" in models
|
| 272 |
+
assert "spacy_fr" not in models
|
| 273 |
+
assert "spacy_en" not in models
|
| 274 |
|
| 275 |
+
# Si service healthy, le modele doit etre OK
|
| 276 |
if health["status"] == "healthy":
|
|
|
|
|
|
|
| 277 |
assert "✅" in models["fasttext"]
|
| 278 |
|
| 279 |
|
|
@@ -248,8 +248,11 @@ class TestRead:
|
|
| 248 |
law = await law_service.get_law(created_law.id, include_category=True)
|
| 249 |
|
| 250 |
# Assert
|
|
|
|
|
|
|
| 251 |
assert law.category is not None
|
| 252 |
-
assert law.category.
|
|
|
|
| 253 |
|
| 254 |
async def test_get_law_not_found(self, law_service):
|
| 255 |
"""Test that fetching non-existent law raises error."""
|
|
@@ -749,13 +752,20 @@ class TestCategories:
|
|
| 749 |
assert category.name == "Nouvelle catégorie"
|
| 750 |
assert category.description == "Description de test"
|
| 751 |
|
| 752 |
-
async def test_list_categories(self, law_service,
|
| 753 |
"""Test listing all categories with law counts."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 754 |
# Act
|
| 755 |
categories = await law_service.list_categories()
|
| 756 |
|
| 757 |
# Assert
|
| 758 |
-
assert
|
|
|
|
| 759 |
assert all(hasattr(cat, "law_count") for cat in categories)
|
| 760 |
|
| 761 |
|
|
|
|
| 248 |
law = await law_service.get_law(created_law.id, include_category=True)
|
| 249 |
|
| 250 |
# Assert
|
| 251 |
+
# Le nom vient du jeu de categories seme par conftest ; le figer en dur
|
| 252 |
+
# ("Droit civil" contre "Droit Civil") ne testait que la casse du seed.
|
| 253 |
assert law.category is not None
|
| 254 |
+
assert law.category.id == sample_law_data_french.category_id
|
| 255 |
+
assert law.category.name == sample_categories[0].name
|
| 256 |
|
| 257 |
async def test_get_law_not_found(self, law_service):
|
| 258 |
"""Test that fetching non-existent law raises error."""
|
|
|
|
| 752 |
assert category.name == "Nouvelle catégorie"
|
| 753 |
assert category.description == "Description de test"
|
| 754 |
|
| 755 |
+
async def test_list_categories(self, law_service, db_session):
|
| 756 |
"""Test listing all categories with law counts."""
|
| 757 |
+
# Le nombre attendu est lu en base : conftest seme les 12 categories de
|
| 758 |
+
# reference, et un total en dur (3) cassait des que le seed evoluait.
|
| 759 |
+
from sqlalchemy import func, select
|
| 760 |
+
|
| 761 |
+
expected = await db_session.scalar(select(func.count()).select_from(Category))
|
| 762 |
+
|
| 763 |
# Act
|
| 764 |
categories = await law_service.list_categories()
|
| 765 |
|
| 766 |
# Assert
|
| 767 |
+
assert expected > 0
|
| 768 |
+
assert len(categories) == expected
|
| 769 |
assert all(hasattr(cat, "law_count") for cat in categories)
|
| 770 |
|
| 771 |
|