import time from pathlib import Path from app.classifier import classify_batch, classify_mail from app.db import save_classement_manuel, get_classement, add_regle from app.mirror_client import MirrorClient STATIC = Path(__file__).resolve().parent.parent / "app" / "static" def _mail(i, objet="Bonjour", tags=None, exp="a@b.tn"): return {"message_id": "m%d" % i, "date": "2026-11-17T09:%02d:00+01:00" % i, "expediteur": exp, "objet": objet, "etiquettes": tags or []} def test_lot_equivalent_au_classement_mail_par_mail(temp_db): mails = [_mail(1, tags=["tunis"]), _mail(2, objet=""), _mail(3), _mail(4, tags=["sans_objet"])] lot = classify_batch(mails, db_path=temp_db) seuls = [classify_mail(m, db_path=temp_db) for m in mails] assert [(c["message_id"], c["categorie"], c["source"]) for c in lot] == [(c["message_id"], c["categorie"], c["source"]) for c in seuls] def test_lot_sans_ecriture_si_inchange(temp_db): mails = [_mail(i) for i in range(1, 6)] premier = classify_batch(mails, db_path=temp_db) time.sleep(1.1) second = classify_batch(mails, db_path=temp_db) assert [c["horodatage"] for c in premier] == [c["horodatage"] for c in second] def test_lot_ne_touche_pas_au_classement_manuel(temp_db): classify_batch([_mail(1, tags=["tunis"])], db_path=temp_db) save_classement_manuel("m1", "CI", expediteur="a@b.tn", objet="Bonjour", date_mail="2026-11-17T09:01:00+01:00", db_path=temp_db) res = classify_batch([_mail(1, tags=["tunis"])], db_path=temp_db) assert res[0]["categorie"] == "CI" and res[0]["source"] == "manuel" assert get_classement("m1", temp_db)["categorie"] == "CI" def test_lot_conserve_traite_quand_la_regle_change(temp_db): classify_batch([_mail(1)], db_path=temp_db) from app.db import get_connection with get_connection(temp_db) as conn: conn.execute("UPDATE classements SET traite = 1 WHERE message_id = 'm1'") add_regle(categorie="CI", expediteur="a@b.tn", mot_cle=None, statut="active", db_path=temp_db) res = classify_batch([_mail(1)], db_path=temp_db) assert res[0]["categorie"] == "CI" and res[0]["traite"] is True def test_lot_ignore_un_mail_sans_identifiant(temp_db): assert classify_batch([{"expediteur": "x"}], db_path=temp_db) == [] def test_lecture_miroir_une_seule_cle_et_rafraichissement_force(monkeypatch): appels = [] c = MirrorClient(base_url="http://x/mcp", token="t") monkeypatch.setattr(c, "call_tool", lambda nom, args=None, use_cache=True, force=False: appels.append((nom, dict(args or {}), force)) or []) c.get_latest_mails(folder="*", n=200) c.get_latest_mails(folder="*", n=400) c.rafraichir_derniers() assert appels[0][1] == appels[1][1] == appels[2][1] assert appels[0][1]["n"] == 100 and appels[2][2] is True and appels[0][2] is False def test_onglet_tri_rouvert_sans_rechargement_sous_30_secondes(): js = (STATIC / "app.js").read_text(encoding="utf-8") assert "S.chargeJour === S.jour && Date.now() - S.chargeA < 30000" in js