# đŸ§Ș StratĂ©gie de Tests - Rakuten Product Classifier ## Executive Summary Ce document dĂ©finit une stratĂ©gie de tests **enterprise-grade** pour garantir la qualitĂ©, la fiabilitĂ© et la maintenabilitĂ© de l'application Rakuten Product Classifier. **Objectif de couverture**: ≄ 85% du code critique --- ## 📊 Pyramide des Tests ``` ┌─────────────────┐ │ E2E Tests │ ← 5% (Playwright) │ (UI/Browser) │ ├────────────────── │ Integration │ ← 20% (Streamlit + ML) │ Tests │ ├────────────────── │ ML-Specific │ ← 25% (Model Quality) │ Tests │ ├────────────────── │ │ │ Unit Tests │ ← 50% (Functions/Classes) │ │ └─────────────────┘ ``` --- ## 🎯 1. TESTS UNITAIRES (Unit Tests) ### 1.1 Module `utils/mock_classifier.py` | Test ID | Fonction testĂ©e | Description | PrioritĂ© | |---------|----------------|-------------|----------| | UT-MC-001 | `DemoClassifier.__init__` | Initialisation avec/sans config | HIGH | | UT-MC-002 | `DemoClassifier.predict(text=...)` | PrĂ©diction texte seul | HIGH | | UT-MC-003 | `DemoClassifier.predict(image=...)` | PrĂ©diction image seule | HIGH | | UT-MC-004 | `DemoClassifier.predict(text, image)` | PrĂ©diction multimodale | HIGH | | UT-MC-005 | `ClassificationResult` | Dataclass attributes | MEDIUM | | UT-MC-006 | `_generate_predictions` | Distribution probabilitĂ©s | HIGH | | UT-MC-007 | `ModelConfig` | Validation dataclass | MEDIUM | | UT-MC-008 | `TEXT_MODELS` | 3 modĂšles texte prĂ©sents | HIGH | | UT-MC-009 | `IMAGE_MODELS` | 3 modĂšles image prĂ©sents | HIGH | | UT-MC-010 | `MultiModelClassifier` | PrĂ©dictions multi-modĂšles | HIGH | **Assertions clĂ©s**: ```python # UT-MC-002: PrĂ©diction texte def test_predict_text_returns_valid_result(): clf = DemoClassifier() result = clf.predict(text="iPhone 15 Pro Max") assert result is not None assert result.category in CATEGORY_MAPPING.keys() assert 0.0 <= result.confidence <= 1.0 assert len(result.top_k_predictions) == 5 assert sum(p[1] for p in result.top_k_predictions) <= 1.0 assert result.source in ["mock_text", "text", "demo"] ``` ### 1.2 Module `utils/category_mapping.py` | Test ID | Fonction testĂ©e | Description | PrioritĂ© | |---------|----------------|-------------|----------| | UT-CM-001 | `CATEGORY_MAPPING` | 27 catĂ©gories prĂ©sentes | HIGH | | UT-CM-002 | `get_category_info(code)` | Retourne (name, full, emoji) | HIGH | | UT-CM-003 | `get_category_info(invalid)` | Gestion code invalide | MEDIUM | | UT-CM-004 | `get_category_emoji(code)` | Retourne emoji correct | LOW | | UT-CM-005 | `get_all_categories()` | Retourne dict complet | MEDIUM | **Assertions clĂ©s**: ```python # UT-CM-001: VĂ©rification 27 catĂ©gories def test_category_mapping_has_27_categories(): assert len(CATEGORY_MAPPING) == 27 # UT-CM-002: Structure correcte def test_get_category_info_returns_tuple(): name, full, emoji = get_category_info("2583") assert isinstance(name, str) assert isinstance(full, str) assert len(emoji) > 0 # Emoji prĂ©sent ``` ### 1.3 Module `utils/preprocessing.py` | Test ID | Fonction testĂ©e | Description | PrioritĂ© | |---------|----------------|-------------|----------| | UT-PP-001 | `preprocess_product_text` | Nettoyage HTML | HIGH | | UT-PP-002 | `preprocess_product_text` | Combinaison designation+description | HIGH | | UT-PP-003 | `preprocess_product_text` | Gestion texte vide | MEDIUM | | UT-PP-004 | `preprocess_product_text` | CaractĂšres spĂ©ciaux | MEDIUM | | UT-PP-005 | `validate_text_input` | Validation longueur | HIGH | | UT-PP-006 | `clean_html` | Suppression balises | HIGH | **Cas de test**: ```python @pytest.mark.parametrize("input_text,expected_contains", [ ("

Test

", "Test"), # HTML removal (" spaces ", "spaces"), # Trim ("UPPERCASE", "uppercase"), # Lowercase (si applicable) ("", ""), # Empty string (None, ""), # None handling ]) def test_preprocess_handles_various_inputs(input_text, expected_contains): result = preprocess_product_text(input_text, "") if expected_contains: assert expected_contains in result.lower() ``` ### 1.4 Module `utils/image_utils.py` | Test ID | Fonction testĂ©e | Description | PrioritĂ© | |---------|----------------|-------------|----------| | UT-IU-001 | `load_image_from_upload` | Chargement JPEG | HIGH | | UT-IU-002 | `load_image_from_upload` | Chargement PNG | HIGH | | UT-IU-003 | `validate_image` | Image valide | HIGH | | UT-IU-004 | `validate_image` | Image trop petite | MEDIUM | | UT-IU-005 | `validate_image` | Image trop grande | MEDIUM | | UT-IU-006 | `get_image_info` | MĂ©tadonnĂ©es correctes | LOW | | UT-IU-007 | `resize_image` | Redimensionnement | MEDIUM | ### 1.5 Module `utils/data_loader.py` | Test ID | Fonction testĂ©e | Description | PrioritĂ© | |---------|----------------|-------------|----------| | UT-DL-001 | `is_data_available` | DĂ©tection donnĂ©es rĂ©elles | HIGH | | UT-DL-002 | `get_dataset_summary` | Retourne dict valide | HIGH | | UT-DL-003 | `get_category_distribution` | DataFrame correct | HIGH | | UT-DL-004 | `get_text_statistics` | Stats texte | MEDIUM | | UT-DL-005 | `load_training_data` | Fallback mode dĂ©mo | HIGH | ### 1.6 Module `config.py` | Test ID | Fonction testĂ©e | Description | PrioritĂ© | |---------|----------------|-------------|----------| | UT-CF-001 | `APP_CONFIG` | ClĂ©s requises prĂ©sentes | HIGH | | UT-CF-002 | `MODEL_CONFIG` | Configuration modĂšle | HIGH | | UT-CF-003 | `THEME` | Couleurs dĂ©finies | LOW | | UT-CF-004 | `ASSETS_DIR` | Path existe | MEDIUM | --- ## 🔗 2. TESTS D'INTÉGRATION (Integration Tests) ### 2.1 Tests de chargement des pages | Test ID | Page testĂ©e | Description | PrioritĂ© | |---------|-------------|-------------|----------| | IT-PG-001 | `app.py` | Page accueil charge sans erreur | CRITICAL | | IT-PG-002 | `1_📊_DonnĂ©es.py` | Page donnĂ©es charge | CRITICAL | | IT-PG-003 | `2_⚙_Preprocessing.py` | Page preprocessing charge | CRITICAL | | IT-PG-004 | `3_🧠_ModĂšles.py` | Page modĂšles charge | CRITICAL | | IT-PG-005 | `4_🔍_DĂ©mo.py` | Page dĂ©mo charge | CRITICAL | | IT-PG-006 | `5_📈_Performance.py` | Page performance charge | CRITICAL | | IT-PG-007 | `6_💡_Conclusions.py` | Page conclusions charge | CRITICAL | **ImplĂ©mentation avec `streamlit.testing`**: ```python from streamlit.testing.v1 import AppTest def test_home_page_loads(): """Test que la page d'accueil charge sans erreur.""" at = AppTest.from_file("app.py") at.run(timeout=30) assert not at.exception assert "Rakuten" in at.markdown[0].value def test_demo_page_classification_flow(): """Test du flow complet de classification.""" at = AppTest.from_file("pages/4_🔍_DĂ©mo.py") at.run() # Simuler saisie texte at.text_input[0].set_value("iPhone 15 Pro Max") at.text_area[0].set_value("Smartphone Apple derniĂšre gĂ©nĂ©ration") at.button[0].click() at.run() assert not at.exception # VĂ©rifier qu'un rĂ©sultat est affichĂ© assert any("CatĂ©gorie" in str(m.value) for m in at.markdown) ``` ### 2.2 Tests de Session State | Test ID | Description | PrioritĂ© | |---------|-------------|----------| | IT-SS-001 | Persistance du classifier entre pages | HIGH | | IT-SS-002 | Historique des classifications | HIGH | | IT-SS-003 | SĂ©lection de modĂšle persiste | HIGH | | IT-SS-004 | Reset session fonctionne | MEDIUM | ### 2.3 Tests de Navigation | Test ID | Description | PrioritĂ© | |---------|-------------|----------| | IT-NV-001 | Navigation accueil → dĂ©mo | HIGH | | IT-NV-002 | Navigation accueil → donnĂ©es | HIGH | | IT-NV-003 | Navigation dĂ©mo → comparaison | HIGH | | IT-NV-004 | Sidebar navigation | MEDIUM | ### 2.4 Tests d'intĂ©gration Classifier + UI | Test ID | Description | PrioritĂ© | |---------|-------------|----------| | IT-CL-001 | Classification texte end-to-end | CRITICAL | | IT-CL-002 | Classification image end-to-end | CRITICAL | | IT-CL-003 | Changement de modĂšle | HIGH | | IT-CL-004 | Comparaison 3 modĂšles simultanĂ©s | HIGH | --- ## đŸ€– 3. TESTS SPÉCIFIQUES ML (Machine Learning Tests) ### 3.1 Tests de Performance du ModĂšle (Model Quality Gates) | Test ID | MĂ©trique | Seuil minimum | PrioritĂ© | |---------|----------|---------------|----------| | ML-PF-001 | Accuracy globale | ≄ 75% | CRITICAL | | ML-PF-002 | F1-Score macro | ≄ 70% | CRITICAL | | ML-PF-003 | F1-Score weighted | ≄ 75% | HIGH | | ML-PF-004 | Precision macro | ≄ 70% | HIGH | | ML-PF-005 | Recall macro | ≄ 65% | HIGH | **ImplĂ©mentation**: ```python import pytest from sklearn.metrics import accuracy_score, f1_score, classification_report class TestModelPerformance: """Tests de qualitĂ© du modĂšle avec seuils minimaux.""" ACCURACY_THRESHOLD = 0.75 F1_MACRO_THRESHOLD = 0.70 @pytest.fixture(scope="class") def model_predictions(self, test_dataset): """GĂ©nĂšre les prĂ©dictions sur le jeu de test.""" clf = load_production_model() X_test, y_true = test_dataset y_pred = clf.predict(X_test) return y_true, y_pred def test_accuracy_above_threshold(self, model_predictions): """L'accuracy doit ĂȘtre ≄ 75%.""" y_true, y_pred = model_predictions accuracy = accuracy_score(y_true, y_pred) assert accuracy >= self.ACCURACY_THRESHOLD, \ f"Accuracy {accuracy:.2%} below threshold {self.ACCURACY_THRESHOLD:.2%}" def test_f1_macro_above_threshold(self, model_predictions): """Le F1-score macro doit ĂȘtre ≄ 70%.""" y_true, y_pred = model_predictions f1 = f1_score(y_true, y_pred, average='macro') assert f1 >= self.F1_MACRO_THRESHOLD, \ f"F1-macro {f1:.2%} below threshold {self.F1_MACRO_THRESHOLD:.2%}" ``` ### 3.2 Tests de Non-RĂ©gression (Regression Tests) | Test ID | Description | PrioritĂ© | |---------|-------------|----------| | ML-RG-001 | Accuracy ne baisse pas vs baseline | CRITICAL | | ML-RG-002 | F1-score ne baisse pas | CRITICAL | | ML-RG-003 | PrĂ©dictions identiques pour inputs fixes | HIGH | | ML-RG-004 | Distribution des classes stable | MEDIUM | **ImplĂ©mentation avec snapshot**: ```python import json from pathlib import Path BASELINE_FILE = Path("tests/baselines/model_baseline.json") class TestModelRegression: """Tests de non-rĂ©gression du modĂšle.""" REGRESSION_TOLERANCE = 0.02 # 2% de tolĂ©rance @pytest.fixture def baseline_metrics(self): """Charge les mĂ©triques de rĂ©fĂ©rence.""" with open(BASELINE_FILE) as f: return json.load(f) def test_no_accuracy_regression(self, current_metrics, baseline_metrics): """L'accuracy ne doit pas baisser de plus de 2%.""" current = current_metrics["accuracy"] baseline = baseline_metrics["accuracy"] assert current >= baseline - self.REGRESSION_TOLERANCE, \ f"Regression detected: {current:.2%} vs baseline {baseline:.2%}" def test_deterministic_predictions(self): """MĂȘmes inputs = mĂȘmes outputs (dĂ©terminisme).""" clf = DemoClassifier(seed=42) input_text = "Console PlayStation 5" result1 = clf.predict(text=input_text) result2 = clf.predict(text=input_text) assert result1.category == result2.category assert abs(result1.confidence - result2.confidence) < 0.001 ``` ### 3.3 Tests de Robustesse (Robustness Tests) | Test ID | Cas de test | Comportement attendu | PrioritĂ© | |---------|-------------|---------------------|----------| | ML-RB-001 | Texte vide | Retourne prĂ©diction par dĂ©faut | HIGH | | ML-RB-002 | Texte trĂšs long (10K chars) | Tronque et prĂ©dit | MEDIUM | | ML-RB-003 | CaractĂšres spĂ©ciaux/emojis | Nettoie et prĂ©dit | MEDIUM | | ML-RB-004 | Image corrompue | Erreur gracieuse | HIGH | | ML-RB-005 | Image trĂšs petite (10x10) | Erreur ou upscale | MEDIUM | | ML-RB-006 | Image trĂšs grande (8000x8000) | Redimensionne | MEDIUM | | ML-RB-007 | Texte multilingue | Traduit et prĂ©dit | HIGH | | ML-RB-008 | HTML malicieux | Sanitize et prĂ©dit | HIGH | **ImplĂ©mentation**: ```python class TestModelRobustness: """Tests de robustesse du modĂšle face aux edge cases.""" @pytest.mark.parametrize("edge_case_text", [ "", # Empty " " * 100, # Whitespace only "a" * 10000, # Very long "", # XSS attempt "đŸŽźđŸ“±đŸ’»đŸ–„ïž", # Emojis only "ä»·æ ŒäŸżćźœèŽšé‡ć„œ", # Chinese "ĐŠĐ”Đœa Ń…ĐŸŃ€ĐŸŃˆĐ°Ń", # Russian None, # None value ]) def test_handles_edge_case_text(self, edge_case_text): """Le modĂšle gĂšre les cas limites sans crash.""" clf = DemoClassifier() # Ne doit pas lever d'exception try: result = clf.predict(text=edge_case_text or "") assert result is not None assert result.category in CATEGORY_MAPPING except ValueError: pass # ValueError acceptable pour entrĂ©e invalide def test_handles_adversarial_input(self): """Test d'input adversarial.""" clf = DemoClassifier() # Texte conçu pour confondre le modĂšle adversarial = "livre console telephone jardin piscine figurine" result = clf.predict(text=adversarial) # Doit quand mĂȘme retourner une prĂ©diction valide assert result.category in CATEGORY_MAPPING # Confiance devrait ĂȘtre plus basse assert result.confidence < 0.95 ``` ### 3.4 Tests de Consistance Inter-ModĂšles | Test ID | Description | PrioritĂ© | |---------|-------------|----------| | ML-CS-001 | 3 modĂšles texte donnent top-3 similaires | MEDIUM | | ML-CS-002 | 3 modĂšles image donnent top-3 similaires | MEDIUM | | ML-CS-003 | CorrĂ©lation des confidences entre modĂšles | LOW | ### 3.5 Tests de Performance (Latency/Throughput) | Test ID | MĂ©trique | Seuil | PrioritĂ© | |---------|----------|-------|----------| | ML-LT-001 | Latence infĂ©rence texte | < 100ms | HIGH | | ML-LT-002 | Latence infĂ©rence image | < 500ms | HIGH | | ML-LT-003 | Throughput batch 100 | > 10/s | MEDIUM | | ML-LT-004 | MĂ©moire max | < 2 GB | MEDIUM | **ImplĂ©mentation**: ```python import time import pytest class TestInferencePerformance: """Tests de performance d'infĂ©rence.""" MAX_TEXT_LATENCY_MS = 100 MAX_IMAGE_LATENCY_MS = 500 def test_text_inference_latency(self): """L'infĂ©rence texte doit ĂȘtre < 100ms.""" clf = DemoClassifier() text = "Console PlayStation 5 nouvelle gĂ©nĂ©ration" # Warmup clf.predict(text=text) # Mesure start = time.perf_counter() for _ in range(100): clf.predict(text=text) elapsed = (time.perf_counter() - start) * 1000 / 100 # ms par infĂ©rence assert elapsed < self.MAX_TEXT_LATENCY_MS, \ f"Text inference too slow: {elapsed:.1f}ms > {self.MAX_TEXT_LATENCY_MS}ms" @pytest.mark.slow def test_batch_throughput(self): """Le throughput batch doit ĂȘtre > 10 prĂ©dictions/seconde.""" clf = DemoClassifier() texts = [f"Product {i}" for i in range(100)] start = time.perf_counter() for text in texts: clf.predict(text=text) elapsed = time.perf_counter() - start throughput = len(texts) / elapsed assert throughput > 10, f"Throughput too low: {throughput:.1f}/s" ``` ### 3.6 Tests de Data Quality (Validation des donnĂ©es) | Test ID | Description | PrioritĂ© | |---------|-------------|----------| | ML-DQ-001 | Pas de NaN dans features | CRITICAL | | ML-DQ-002 | Toutes les catĂ©gories prĂ©sentes | HIGH | | ML-DQ-003 | Distribution des classes cohĂ©rente | MEDIUM | | ML-DQ-004 | Pas de doublons dans test set | HIGH | | ML-DQ-005 | Train/Test split correct (pas de fuite) | CRITICAL | **ImplĂ©mentation avec Great Expectations style**: ```python class TestDataQuality: """Tests de qualitĂ© des donnĂ©es.""" def test_no_nan_in_features(self, training_data): """Aucune valeur NaN dans les features.""" X, y = training_data assert not X.isnull().any().any(), "NaN values found in features" def test_all_categories_represented(self, training_data): """Les 27 catĂ©gories sont reprĂ©sentĂ©es.""" X, y = training_data unique_categories = y['prdtypecode'].unique() assert len(unique_categories) == 27, \ f"Expected 27 categories, found {len(unique_categories)}" def test_no_data_leakage(self, train_data, test_data): """Pas de fuite de donnĂ©es train→test.""" train_ids = set(train_data.index) test_ids = set(test_data.index) overlap = train_ids & test_ids assert len(overlap) == 0, f"Data leakage: {len(overlap)} samples in both sets" ``` --- ## 🌐 4. TESTS END-TO-END (E2E Tests) ### 4.1 Tests Playwright (Browser Automation) | Test ID | ScĂ©nario | PrioritĂ© | |---------|----------|----------| | E2E-001 | Parcours complet: accueil → classification → rĂ©sultat | CRITICAL | | E2E-002 | Upload image et classification | HIGH | | E2E-003 | Comparaison des 3 modĂšles | HIGH | | E2E-004 | Navigation complĂšte (6 pages) | HIGH | | E2E-005 | Galerie d'exemples | MEDIUM | | E2E-006 | Export CSV distribution | LOW | **ImplĂ©mentation**: ```python from playwright.sync_api import Page, expect import pytest class TestE2EClassification: """Tests E2E avec Playwright.""" BASE_URL = "http://localhost:8501" def test_full_classification_journey(self, page: Page): """Parcours utilisateur complet.""" # 1. Page d'accueil page.goto(self.BASE_URL) expect(page.locator("text=Rakuten")).to_be_visible() # 2. Click sur "Classifier un Produit" page.click("button:has-text('Classifier')") page.wait_for_url("**/4_*DĂ©mo*") # 3. Remplir le formulaire page.fill("input[aria-label='DĂ©signation']", "iPhone 15 Pro Max") page.fill("textarea[aria-label='Description']", "Smartphone Apple") # 4. Classifier page.click("button:has-text('Classifier le Produit')") # 5. VĂ©rifier le rĂ©sultat expect(page.locator(".result-card")).to_be_visible(timeout=10000) expect(page.locator("text=CatĂ©gorie")).to_be_visible() def test_model_comparison(self, page: Page): """Test comparaison des modĂšles.""" page.goto(f"{self.BASE_URL}/3_🧠_ModĂšles") # SĂ©lectionner mode texte page.click("text=ModĂšles Texte") # Remplir input page.fill("input", "Console PlayStation 5") # Lancer comparaison page.click("button:has-text('Comparer')") # VĂ©rifier 3 rĂ©sultats expect(page.locator(".model-card")).to_have_count(3) ``` ### 4.2 Tests de Snapshot UI ```python def test_home_page_snapshot(page: Page, assert_snapshot): """Snapshot de la page d'accueil.""" page.goto(BASE_URL) page.wait_for_load_state("networkidle") assert_snapshot(page.screenshot(), "home_page.png") ``` --- ## 🔒 5. TESTS DE SÉCURITÉ (Security Tests) | Test ID | VulnĂ©rabilitĂ© | Test | PrioritĂ© | |---------|--------------|------|----------| | SEC-001 | XSS | Injection script dans input | HIGH | | SEC-002 | Path Traversal | Upload fichier malicieux | HIGH | | SEC-003 | DoS | Input trĂšs volumineux | MEDIUM | | SEC-004 | Injection | CaractĂšres spĂ©ciaux SQL-like | LOW | ```python class TestSecurity: """Tests de sĂ©curitĂ©.""" XSS_PAYLOADS = [ "", "", "javascript:alert('xss')", "", ] @pytest.mark.parametrize("payload", XSS_PAYLOADS) def test_xss_prevention(self, payload): """Les payloads XSS sont sanitizĂ©s.""" result = preprocess_product_text(payload, "") assert "