SPB Git

Repository Public

test_v2.py 11.2 KB 228 lines python

1# -----------------------------------------------------------------------------2# Food-Ka v2 — tests du backend autonome (aucun appel réseau, base temporaire)3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# -----------------------------------------------------------------------------5import json6import time78import pytest910from foodka import catalogue as C11from foodka import db, public, services, taxonomie, unites12from foodka.schema import Product131415# -- formats et prix unitaires ---------------------------------------------------16@pytest.mark.parametrize("label,qte,base,nb", [17    ("2x500 g", 1000, "g", 2), ("12 × 355 mL", 4260, "ml", 12),18    ("1.81 kg, 0,39 $/100g", 1810, "g", 1), ("env. 1,2 kg", 1200, "g", 1),19    ("Une barquette contient en moyenne 1200 g", 1200, "g", 1),20    ("10 unités - 375 g", 375, "g", 1), ("100 ea, 0,05 $/1ch", 100, "un", 1),21])22def test_format_lu(label, qte, base, nb):23    f = unites.lire_format(label)24    assert round(f.qte) == qte and f.base == base and f.nb == nb252627def test_format_variable_ou_absent():28    assert unites.lire_format("425 ou 454 g").variable29    assert unites.lire_format("200 à 340 g").qte is None30    assert not unites.lire_format("5,49 $/1kg 2,49 $/1lb")        # prix au kilo, pas un format31    assert unites.lire_format("", "Pain 100% blé entier").qte is None32    assert unites.lire_format("", "Noodle King, Beef, 85 g").origine == "name"333435def test_prix_unitaire():36    pu = unites.prix_unitaire(7.0, unites.lire_format("1.81 kg, 0,39 $/100g"),37                              size_label="1.81 kg, 0,39 $/100g")38    assert pu == {"value": 0.39, "unit": "100 g", "label": "0,39 $ / 100 g", "basis": "store"}39    # produit au poids : le prix à la pièce est une estimation, le prix au kilo fait foi40    pu = unites.prix_unitaire(1.58, unites.lire_format("6,59 $/1kg 2,99 $/1lb"),41                              size_label="6,59 $/1kg 2,99 $/1lb")42    assert pu["value"] == 0.659 and pu["unit"] == "100 g"43    # unité fausse affichée par l'enseigne (« /100 kg ») : on recalcule44    pu = unites.prix_unitaire(7.99, unites.lire_format("1 kg"), unit_price_label="0,80 $ /100 kg")45    assert pu["basis"] == "computed" and pu["value"] == 0.79946    assert unites.prix_unitaire(6.0, unites.lire_format("2 L"))["unit"] == "L"47    assert unites.prix_unitaire(3.99, unites.lire_format("425 ou 454 g")) is None484950def test_extraire_format():51    f, reste = unites.extraire_format("lait 2 % 2 L")52    assert f.qte == 2000 and f.base == "ml" and reste.split() == ["lait", "2", "%"]535455# -- rayons ---------------------------------------------------------------------------56def test_classer():57    assert taxonomie.classer("Lait 2 % 4 L", "Produits laitiers et œufs") == (58        "Produits laitiers et œufs", "Lait")59    assert taxonomie.classer("Poulet entier", "Autres")[0] == "Viandes et volailles"60    assert taxonomie.classer("Savon au lait de chèvre", "Autres")[0] == "Santé et beauté"61    assert taxonomie.classer("Beurre d'arachide croquant", "Autres")[1] == "Tartinades et confitures"62    assert taxonomie.enseigne_de("metro_flyer") == "metro"636465# -- règle publique -------------------------------------------------------------------66def _ev(**kw):67    base = dict(source="metro", name="Lait 2 %", price=4.5, rayon="Produits laitiers et œufs",68                keywords=[], details={}, sources_actives={"metro", "giant_tiger"})69    base.update(kw)70    return public.evaluer(**base)717273def test_regle_publique():74    assert _ev() is None75    assert _ev(source="inconnue") == "enseigne_inconnue"76    assert _ev(name="") == "nom_illisible"77    assert _ev(price=None) == "sans_prix"78    assert _ev(price=0.01) == "prix_implausible"79    assert _ev(price=899.0) == "prix_implausible"80    assert _ev(price=899.0, rayon="Alcool") is None81    assert _ev(source="giant_tiger", keywords=["mms_province_code:ON"]) == "hors_quebec"82    assert _ev(source="giant_tiger", keywords=["mms_province_code:ON", "mms_province_code:QC"]) is None83    assert _ev(details={"valid_to": "2020-01-01T00:00:00-05:00"}) == "circulaire_echue"84    assert _ev(details={"valid_from": "2099-01-01T00:00:00-05:00",85                        "valid_to": "2099-01-08T00:00:00-05:00"}) == "circulaire_a_venir"86    assert _ev(name="Carte-cadeau Metro 50 $") == "hors_epicerie"878889# -- appariement par le nom --------------------------------------------------------------90def test_meme_nom():91    assert C.meme_nom("croustille nature", "croustilles nature")92    assert not C.meme_nom("beurre herbe non nourrie sale", "beurre herbe nourrie sale")93    assert not C.meme_nom("aile americaine douce poulet", "aile americaine piquante poulet")94    assert not C.meme_nom("lait 2", "lait 1")959697# -- catalogue sur une base temporaire ------------------------------------------------------98@pytest.fixture99def cat(tmp_path, monkeypatch):100    monkeypatch.setattr(db, "DB_PATH", tmp_path / "t.db")101    reg = tmp_path / "sources.json"102    reg.write_text(json.dumps({"sources": [103        {"id": s, "name": n, "status": "actif", "region": "Tout le Québec", "url": "u"}104        for s, n in [("metro", "Metro"), ("superc", "Super C"), ("maxi", "Maxi"),105                     ("provigo", "Provigo"), ("iga", "IGA"), ("metro_flyer", "Metro (circulaire)")]]}))106    monkeypatch.setattr(C, "SOURCES_PATH", reg)107    con = db.connect()108109    def P_(src, ext, name, price, **kw):110        return Product(source=src, external_id=ext, url="https://x/" + ext, name=name,111                       price=price, **kw).finalize()112113    for src, prix in (("metro", 5.49), ("superc", 4.99)):114        db.sync_source(con, src, [115            P_(src, "059749961905", "Beurre d'arachide crémeux", prix, brand="Kraft",116               size_label="1 kg", category="Garde-manger"),117            P_(src, "L" + src, "Lait 2 %", 4.5 if src == "metro" else 4.2, brand="Québon",118               size_label="2 L", category="Produits laitiers et œufs"),119            P_(src, "X" + src, "Carte-cadeau 50 $", 50.0),120        ])121    db.sync_source(con, "maxi", [122        P_("maxi", "21_EA", "Lait 2%", 3.99, brand="Québon", size_label="2 l, 0,20 $/100ml",123           category="Produits laitiers et œufs"),124        P_("maxi", "22_EA", "Lait 2%", 3.99, brand="Québon", size_label="2 l, 0,20 $/100ml",125           category="Produits laitiers et œufs"),                       # doublon126        P_("maxi", "23_EA", "Pommes Gala", 1.58, size_label="6,59 $/1kg 2,99 $/1lb",127           category="Fruits et légumes"),128    ])129    db.sync_source(con, "provigo", [130        P_("provigo", "21_EA", "Lait 2%", 4.79, brand="Québon", size_label="2 l, 0,24 $/100ml",131           category="Produits laitiers et œufs")])132    db.sync_source(con, "iga", [133        P_("iga", "1", "Lait 3,25 %", 4.9, brand="Québon", size_label="2 L",134           category="Produits laitiers et œufs"),135        P_("iga", "2", "Produit sans prix", None)])136    demain = time.strftime("%Y-%m-%dT23:59:59-05:00", time.localtime(time.time() + 3 * 86400))137    hier = time.strftime("%Y-%m-%dT00:00:00-05:00", time.localtime(time.time() - 86400))138    db.sync_source(con, "metro_flyer", [139        P_("metro_flyer", "beurre", "BEURRE D'ARACHIDE CRÉMEUX", 3.99, brand="Kraft",140           size_label="1 kg", on_sale=True, category="Garde-manger",141           details={"flyer_id": 1, "valid_from": hier, "valid_to": demain})])142    # historique : le lait de Metro coûtait 5,50 $ pendant 40 jours puis 4,50 $ depuis 3 jours143    now = time.time()144    con.execute("DELETE FROM price_log WHERE uid='metro:Lmetro'")145    con.execute("INSERT INTO price_log VALUES ('metro:Lmetro', ?, 5.5)", (now - 43 * 86400,))146    con.execute("INSERT INTO price_log VALUES ('metro:Lmetro', ?, 4.5)", (now - 3 * 86400,))147    con.commit()148    con.close()149    return C.construire()150151152def test_public_et_exclus(cat):153    assert len(cat.tous) == 13154    assert len(cat.publics) + sum(cat.exclus.values()) == len(cat.tous)155    assert cat.exclus["hors_epicerie"] == 2 and cat.exclus["sans_prix"] == 1156    assert cat.exclus["doublon"] == 2          # 2e lait Maxi ; beurre Metro du catalogue157    # le rabais de circulaire l'emporte sur le même produit en rayon, dont il garde le prix158    b = cat.get("metro_flyer:beurre")159    assert not b.raison and b.prix_catalogue == 5.49 and b.name == "Beurre d'arachide crémeux"160    assert b.deal["status"] == "verifiee" and b.deal["reference"] == "catalogue"161162163def test_appariement(cat):164    lait = cat.get("maxi:21_EA")165    offres = {o["store"]: o for o in C.offres(cat, lait)}166    assert offres["provigo"]["match"] == "identique"          # même numéro d'article167    assert offres["metro"]["match"] == "meme_produit" and offres["superc"]["match"] == "meme_produit"168    assert "iga" not in offres                                # 3,25 % n'est pas 2 %169    assert lait.carte["compare"]["stores"] == 4 and lait.carte["compare"]["is_best"]170    assert lait.verdict["code"] == "bon" and lait.verdict["vs_stores_pct"] < 0171172173def test_solde_verifie_contre_lhistorique(cat):174    p = cat.get("metro:Lmetro")175    assert p.deal["status"] == "verifiee" and p.deal["reference"] == "historique"176    assert p.deal["reference_price"] == 5.5 and round(p.deal["drop_pct"], 1) == 18.2177178179def test_au_poids(cat):180    p = cat.get("maxi:23_EA")181    assert p.poids and p.pu["value"] == 0.659 and p.pu["basis"] == "store"182183184def test_totaux_concordent(cat):185    total = len(cat.publics)186    assert services.recherche(cat)["total"] == total187    fa = services.facettes(cat)188    assert fa["total"] == total189    assert sum(s["n"] for s in fa["stores"]) == total190    assert sum(c["n"] for c in fa["categories"]) == total191    assert services.sources(cat)["total"] == total192    assert services.enseignes(cat)["n_products"] == total193    assert sum(s["public_products"] for s in services.sources(cat)["sources"]) == total194195196def test_recherche_tolerante(cat):197    r = services.recherche(cat, q="beure arachide")198    assert r["total"] == 2 and "arachide" in r["products"][0]["name"]199    assert services.recherche(cat, q="LAIT", params={"store": "maxi"})["total"] == 1200    assert services.recherche(cat, q="lait", sort="unit_price")["unit_price_unit"] == "L"201    with pytest.raises(services.Invalide):202        services.recherche(cat, sort="n_importe")203204205def test_panier(cat):206    d = services.panier(cat, {"items": [{"id": "maxi:21_EA", "quantity": 2},207                                        {"q": "beurre arachide 1 kg"}]})208    par = {s["store"]: s for s in d["stores"]}209    assert par["metro"]["complete"] and par["metro"]["total"] == round(2 * 4.5 + 3.99, 2)210    assert par["superc"]["complete"] and par["superc"]["total"] == round(2 * 4.2 + 4.99, 2)211    # Maxi n'a pas le beurre : pas de total, seulement un total partiel signalé212    assert not par["maxi"]["complete"] and par["maxi"]["total"] is None213    assert par["maxi"]["missing"][0]["line"] == 1214    assert d["best_single"]["store"] == "metro"215    assert d["best_pair"]["complete"] and d["best_pair"]["total"] == round(2 * 3.99 + 3.99, 2)216    assert d["best_pair"]["savings_vs_best_single"] > 0217    with pytest.raises(services.Invalide):218        services.panier(cat, {"items": []})219220221def test_fiche(cat):222    f = services.fiche(cat, "maxi:21_EA")223    assert f["public"] and f["unit_price"]["unit"] == "L" and len(f["offers"]) == 3224    assert f["history"]["mode"] == "steps"225    g = services.fiche(cat, "maxi:22_EA")226    assert g["public"] is False and g["reason"] == "doublon"227    assert services.fiche(cat, "maxi:inconnu") is None228
Files main
Menu

Theme