|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import unittest |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | +try: |
| 8 | + import shap # noqa: F401 |
| 9 | + import streamlit # noqa: F401 |
| 10 | + |
| 11 | + HAS_DASHBOARD_DEPS = True |
| 12 | +except Exception: # pragma: no cover - streamlit/shap are optional heavy deps |
| 13 | + HAS_DASHBOARD_DEPS = False |
| 14 | + |
| 15 | + |
| 16 | +@unittest.skipUnless(HAS_DASHBOARD_DEPS, "streamlit and shap are required") |
| 17 | +class AppDashboardTests(unittest.TestCase): |
| 18 | + """Smoke tests for app.py helpers; skipped cleanly without streamlit/shap.""" |
| 19 | + |
| 20 | + def test_plot_single_shap_bar_returns_figure(self) -> None: |
| 21 | + import matplotlib |
| 22 | + |
| 23 | + matplotlib.use("Agg") |
| 24 | + import matplotlib.figure |
| 25 | + |
| 26 | + import app |
| 27 | + |
| 28 | + shap_values = np.array([0.5, -0.3, 0.1, 0.0, 0.2]) |
| 29 | + feature_names = np.array(["f0", "f1", "f2", "f3", "f4"]) |
| 30 | + |
| 31 | + fig = app.plot_single_shap_bar(shap_values, feature_names, max_features=3) |
| 32 | + self.assertIsInstance(fig, matplotlib.figure.Figure) |
| 33 | + |
| 34 | + def test_explain_single_transaction_end_to_end(self) -> None: |
| 35 | + import matplotlib |
| 36 | + |
| 37 | + matplotlib.use("Agg") |
| 38 | + import matplotlib.figure |
| 39 | + |
| 40 | + import app |
| 41 | + from src.config import TARGET_COL |
| 42 | + from src.features import build_pipeline |
| 43 | + from src.generate_synthetic_data import generate_synthetic_fraud_dataset |
| 44 | + from src.score_new_transactions import score_dataframe |
| 45 | + |
| 46 | + df = generate_synthetic_fraud_dataset(n_samples=300, fraud_rate=0.2, seed=5) |
| 47 | + X = df.drop(columns=[TARGET_COL]) |
| 48 | + y = df[TARGET_COL] |
| 49 | + |
| 50 | + model = build_pipeline() |
| 51 | + model.fit(X, y) |
| 52 | + |
| 53 | + scored = score_dataframe(df, threshold=0.5, model=model) |
| 54 | + fig, reasons = app.explain_single_transaction(model, scored, 0) |
| 55 | + |
| 56 | + self.assertIsInstance(fig, matplotlib.figure.Figure) |
| 57 | + self.assertIsInstance(reasons, list) |
| 58 | + self.assertTrue(len(reasons) > 0) |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + unittest.main() |
0 commit comments