Spaces:
Running on Zero
Running on Zero
Download tests/test_api.py from Myz0/CV-Matching: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/spaces/Myz0/CV-Matching/resolve/main/tests/test_api.py
- Command line
-
hf download hf://spaces/Myz0/CV-Matching/tests/test_api.py
-
curl -L -o test_api.py https://huggingface.co/spaces/Myz0/CV-Matching/resolve/main/tests/test_api.py
13.8 kB
| """Test de l'application complète (API + interface Gradio + MCP), sans bge-m3 ni réseau. | |
| On remplace le module app.encodeur (qui charge torch et bge-m3) par l'encodeur factice, | |
| et la lecture du dataset Hugging Face par des AVP de test. Le démarrage (lifespan), | |
| toutes les routes et les fonctions de l'interface sont exercés. | |
| Lancer depuis la racine du projet : python -m tests.test_api | |
| """ | |
| import json | |
| import sys | |
| import types | |
| from tests import factices | |
| # 1. Encodeur factice à la place de bge-m3 (avant d'importer app.main) | |
| faux_module = types.ModuleType("app.encodeur") | |
| faux_module.Encodeur = lambda nom: factices.Encodeur() | |
| sys.modules["app.encodeur"] = faux_module | |
| from app import avp_store, config, interface, scoring # noqa: E402 | |
| scoring.SIM_BAS, scoring.SIM_HAUT = 0.15, 0.55 | |
| config.RERANKER_MODEL = "" # pas de reranker (ni téléchargement) | |
| avp_store.lire_avps = lambda: factices.AVPS # pas de téléchargement | |
| from fastapi.testclient import TestClient # noqa: E402 | |
| from app.main import app # noqa: E402 | |
| with TestClient(app) as client: # "with" déclenche le démarrage (lifespan) | |
| h = client.get("/health").json() | |
| print("health:", h) | |
| assert h["nb_avps"] == 4 and h["nb_avps_ouverts"] == 3 | |
| avps = client.get("/avps").json() | |
| assert {a["id_avp"] for a in avps} >= {"3134-26-1269/SR"} | |
| assert next(a for a in avps if a["id_avp"] == "3134-26-1267/SR")["ouvert"] is False | |
| juriste = factices.CVS[0] | |
| r = client.post("/match?top=3", json=juriste) | |
| assert r.status_code == 200, r.text | |
| res = r.json()["resultats"] | |
| print("match:", [(x["titre"], x["score_qualite"], x["ouvert"]) for x in res]) | |
| assert res[0]["id_avp"] == "3134-26-1269/SR" and res[0]["date_limite"] == "2026-12-31" | |
| assert res[0]["libelle"] and res[0]["nb_savoir_faire"] == res[0]["nb_competences"] - 5 | |
| assert len(res[0]["savoir_etre"]) == 5 and h["reranker"] is None | |
| assert len(client.post("/match?inclure_fermes=true", json=juriste).json()["resultats"]) == 4 | |
| assert client.post("/match", json={"basics": {"name": "x"}}).status_code == 422 | |
| r = client.post("/avps/3134-26-1268/SR/candidats", json={"cvs": factices.CVS}) | |
| assert r.status_code == 200, r.text | |
| assert r.json()["candidats"][0]["index"] == 1 | |
| assert client.get("/docs").status_code == 200 | |
| # Version 1 de l'API : /v1/... documentées ; anciennes adresses identiques mais hors de /docs | |
| assert client.get("/v1/health").json()["nb_avps"] == 4 | |
| assert client.post("/v1/match?top=3", json=juriste).json() == client.post("/match?top=3", json=juriste).json() | |
| chemins = client.get("/openapi.json").json()["paths"] | |
| assert "/v1/match" in chemins and "/v1/avps/{id_avp}/candidats" in chemins and "/match" not in chemins, list(chemins) | |
| # Limites : vivier trop grand (422), CV trop long (422), requête trop volumineuse (413, avant lecture) | |
| r = client.post("/v1/avps/3134-26-1268/SR/candidats", json={"cvs": [juriste] * (config.MAX_CV_VIVIER + 1)}) | |
| assert r.status_code == 422, r.text | |
| r = client.post("/v1/match", json={"basics": {"summary": "droit " * (config.MAX_CARACTERES_CV // 6 + 1)}}) | |
| assert r.status_code == 422 and "trop long" in r.text, r.text | |
| r = client.post("/v1/match", content=b" " * (config.MAX_OCTETS_REQUETE + 1), headers={"content-type": "application/json"}) | |
| assert r.status_code == 413, (r.status_code, r.text) | |
| # Clé API : REST, API Gradio et MCP la demandent dès qu'elle est configurée | |
| config.API_KEY = "cle-de-test" | |
| assert client.post("/v1/match", json=juriste).status_code == 401 | |
| assert client.post("/v1/match", json=juriste, headers={"X-API-Key": "cle-de-test"}).status_code == 200 | |
| def appel_gradio(cle=None): | |
| entetes = {"X-API-Key": cle} if cle else {} | |
| ev = client.post("/gradio_api/call/matcher_cv", json={"data": [json.dumps(juriste), False]}, headers=entetes) | |
| assert ev.status_code == 200, ev.text | |
| return client.get(f"/gradio_api/call/matcher_cv/{ev.json()['event_id']}").text | |
| assert "event: error" in appel_gradio() and "Juriste RH" not in appel_gradio("mauvaise") | |
| assert "event: complete" in appel_gradio("cle-de-test") and "Juriste RH" in appel_gradio("cle-de-test") | |
| outils = {t["name"]: t for t in client.get("/gradio_api/mcp/schema").json()} | |
| assert all(outils[n]["meta"].get("headers") == ["x-api-key"] for n in ("matcher_cv", "classer_candidats")), outils | |
| assert all("x_api_key" not in outils[n]["inputSchema"].get("properties", {}) for n in outils) | |
| # Clés par équipe : seule l'empreinte est configurée ; la clé principale marche toujours ; | |
| # une équipe révoquée n'a plus accès, les autres si | |
| from app.routes_api import empreinte, proprietaire | |
| from scripts.cles_api import nouvelle_cle, valeur_secret | |
| cle_hub, cle_rh = nouvelle_cle(), nouvelle_cle() | |
| assert cle_hub.startswith("cvm_") and len(cle_hub) > 40 and cle_hub != cle_rh | |
| registre = {"equipe-hub": {"empreinte": empreinte(cle_hub)}, "equipe-rh": {"empreinte": empreinte(cle_rh)}} | |
| config.API_KEYS_HASH = json.loads(valeur_secret(registre)) | |
| assert cle_hub not in json.dumps(config.API_KEYS_HASH) # la clé n'est jamais gardée | |
| assert proprietaire(cle_hub) == "equipe-hub" and proprietaire("cle-de-test") == "principale" | |
| for cle, code in ((cle_hub, 200), (cle_rh, 200), ("cle-de-test", 200), ("cvm_inventee", 401)): | |
| assert client.post("/v1/match", json=juriste, headers={"X-API-Key": cle}).status_code == code, cle | |
| assert proprietaire("clé-accentuée") is None # caractères non ASCII : refus, pas d'erreur | |
| assert "Juriste RH" in appel_gradio(cle_rh) | |
| assert client.post("/v1/avps/refresh", headers={"X-API-Key": cle_rh}).status_code == 403 # administration : | |
| assert client.post("/v1/avps/refresh", headers={"X-API-Key": "cle-de-test"}).status_code == 200 # clé principale seule | |
| del registre["equipe-hub"]; config.API_KEYS_HASH = json.loads(valeur_secret(registre)) # révocation | |
| assert client.post("/v1/match", json=juriste, headers={"X-API-Key": cle_hub}).status_code == 401 | |
| assert client.post("/v1/match", json=juriste, headers={"X-API-Key": cle_rh}).status_code == 200 | |
| config.API_KEY = None # clés d'équipe seules : toujours exigées | |
| assert client.post("/v1/match", json=juriste).status_code == 401 | |
| config.API_KEYS_HASH = {} | |
| assert client.post("/v1/match", json=juriste).status_code == 200 # aucune clé configurée : ouvert | |
| print("v1, limites, clé API, clés d'équipe : OK") | |
| # Hub de la promotion (faux hub) : candidatures et CV lus avec le jeton hub de l'appelant | |
| import httpx | |
| from app import hub | |
| reseau = factices.CVS[1] | |
| cv_libre = {"identite": {"nom": "Dupont", "prenom": "Léa", "email": "lea@hub.nc"}, # structure libre (n8n) | |
| "experiences": [{"poste": reseau["work"][0]["position"], "missions": reseau["work"][0]["highlights"]}], | |
| "competences": [x["name"] for x in reseau["skills"]], "date_naissance": "1990-01-01"} | |
| profils_hub = {11: {"cvJsonGenere": json.dumps(cv_libre), "cv": None}, # CV n8n, en texte JSON | |
| 12: {"cvJsonGenere": None, "cv": factices.CVS[0]}, # CV saisi, JSON Resume | |
| 13: {"cvJsonGenere": None, "cv": None}, # pas encore de CV | |
| 14: {"cvJsonGenere": None, "cv": factices.CVS[3]}} | |
| candidatures_hub = [ | |
| {"id": 101, "candidat": {"id": 11, "nom": "Dupont", "email": "lea@hub.nc"}, "avpReference": "3134-26-1268/SR", "statut": "EN_ATTENTE"}, | |
| {"id": 102, "candidat": {"id": 12, "nom": "Martin"}, "avpReference": "3134-26-1268/SR", "statut": "VALIDEE"}, | |
| {"id": 103, "candidat": {"id": 13}, "avpReference": "3134-26-1268/SR", "statut": "EN_ATTENTE"}, | |
| {"id": 104, "candidat": {"id": 14}, "avpReference": "3134-26-1268/SR", "statut": "ANNULEE"}, | |
| {"id": 105, "candidat": {"id": 11}, "avpReference": "3134-26-1269/SR", "statut": "EN_ATTENTE"}] | |
| def faux_hub(requete: httpx.Request) -> httpx.Response: | |
| role = {"Bearer jeton-recruteur": "RECRUTEUR", "Bearer jeton-candidat-12": "CANDIDAT"}.get( | |
| requete.headers.get("Authorization")) | |
| if role is None: | |
| return httpx.Response(401) | |
| chemin = requete.url.path | |
| if chemin == "/candidatures": | |
| if role != "RECRUTEUR": | |
| return httpx.Response(403) | |
| page, taille = int(requete.url.params["page"]), 2 # pages de 2 : la pagination est suivie | |
| return httpx.Response(200, json={"contenu": candidatures_hub[(page - 1) * taille: page * taille], "page": page, | |
| "taille": taille, "totalPages": 3, "totalElements": len(candidatures_hub)}) | |
| if chemin.startswith("/profils/"): | |
| uid = int(chemin.rsplit("/", 1)[1]) | |
| if role == "CANDIDAT" and uid != 12: | |
| return httpx.Response(403) | |
| if uid not in profils_hub: | |
| return httpx.Response(404) | |
| return httpx.Response(200, json={"candidat": {"id": uid, "nom": "X", "email": "x@hub.nc"}, **profils_hub[uid]}) | |
| return httpx.Response(404) | |
| hub.TRANSPORT = httpx.MockTransport(faux_hub) | |
| url = "/v1/hub/avps/3134-26-1268/SR/candidatures" | |
| r = client.post(url) | |
| assert r.status_code == 401 and "X-Hub-Token" in r.text, r.text # jamais de compte par défaut | |
| assert client.post(url, headers={"X-Hub-Token": "jeton-candidat-12"}).status_code == 403 # le hub décide | |
| assert client.post(url, headers={"X-Hub-Token": "faux"}).status_code == 401 | |
| assert client.post("/v1/hub/avps/inconnu/candidatures", headers={"X-Hub-Token": "jeton-recruteur"}).status_code == 404 | |
| r = client.post(url, headers={"X-Hub-Token": "Bearer jeton-recruteur"}) # « Bearer » accepté devant | |
| assert r.status_code == 200, r.text | |
| rep = r.json() | |
| lien = {x["index"]: x for x in rep["candidatures_hub"]} | |
| assert sorted(x["candidature_id"] for x in lien.values()) == [101, 102, 103] # ANNULEE exclue, autre AVP exclu | |
| assert lien[rep["candidats"][0]["index"]]["candidature_id"] == 101 # l'ingénieur réseaux en tête | |
| assert [lien[e["index"]]["candidature_id"] for e in rep["ecartes"]] == [103] # profil sans CV : écarté | |
| assert lien[2]["cv_trouve"] is False and lien[1]["statut"] == "VALIDEE" | |
| assert "Dupont" not in r.text and "lea@hub.nc" not in r.text and "1990" not in r.text # identité jamais renvoyée | |
| r = client.post(url + "?inclure_annulees=true", headers={"X-Hub-Token": "jeton-recruteur"}) | |
| assert len(r.json()["candidatures_hub"]) == 4 | |
| m = client.post("/v1/hub/profils/11/match?top=2", headers={"X-Hub-Token": "jeton-recruteur"}) | |
| assert m.status_code == 200 and m.json()["resultats"][0]["id_avp"] == "3134-26-1268/SR", m.text | |
| assert client.post("/v1/hub/profils/13/match", headers={"X-Hub-Token": "jeton-recruteur"}).status_code == 422 | |
| assert client.post("/v1/hub/profils/99/match", headers={"X-Hub-Token": "jeton-recruteur"}).status_code == 404 | |
| assert client.post("/v1/hub/profils/12/match", headers={"X-Hub-Token": "jeton-candidat-12"}).status_code == 200 # le sien | |
| assert client.post("/v1/hub/profils/11/match", headers={"X-Hub-Token": "jeton-candidat-12"}).status_code == 403 | |
| config.API_KEY = "cle-de-test" # la clé du service reste exigée | |
| assert client.post(url, headers={"X-Hub-Token": "jeton-recruteur"}).status_code == 401 | |
| config.API_KEY = None | |
| def injoignable(requete): | |
| raise httpx.ConnectError("hub éteint", request=requete) | |
| hub.TRANSPORT = httpx.MockTransport(injoignable) | |
| assert client.post(url, headers={"X-Hub-Token": "jeton-recruteur"}).status_code == 502 | |
| hub.TRANSPORT = None | |
| doc = client.get("/openapi.json").json() | |
| assert set(doc["components"]["securitySchemes"]) == {"cle_service", "jeton_hub"} # deux champs dans « Authorize » | |
| assert {k for s in doc["paths"]["/v1/hub/avps/{id_avp}/candidatures"]["post"]["security"] for k in s} == {"cle_service", "jeton_hub"} | |
| print("hub de la promotion (faux hub) : OK") | |
| page = client.get("/") | |
| assert page.status_code == 200 and "html" in page.headers["content-type"], page.status_code | |
| print("page / :", page.status_code, page.headers["content-type"]) | |
| # Fonctions de l'interface (celles exposées aussi en MCP) | |
| md = interface.matcher_cv(json.dumps(juriste), False) | |
| assert "Juriste RH" in md and "Point fort" in md, md | |
| assert "illisible" in interface.matcher_cv("{pas du json", False) | |
| md = interface.classer_vivier("3134-26-1270/SR", json.dumps(factices.CVS)) | |
| assert "| 1 |" in md and "Prérequis" in md, md | |
| assert "inconnu" in interface.classer_vivier("nope", json.dumps(factices.CVS)) | |
| print(md[:900]) | |
| # Exemples du projet : 23 CV fictifs chargés, sans le champ _profil (réponse attendue) | |
| if interface.EXEMPLES: | |
| assert all("_profil" not in cv for cv in interface.EXEMPLES.values()) | |
| print(f"{len(interface.EXEMPLES)} CV d'exemple chargés dans l'interface") | |
| # Serveur MCP monté par Gradio | |
| routes = [getattr(x, "path", "") for x in app.routes] | |
| print("routes MCP:", [x for x in routes if "mcp" in x] or "montées sous /", ) | |
| print("\nTEST API OK") | |