262 lines
14 KiB
Python
262 lines
14 KiB
Python
"""Vérifications de la web app, sans appel à claude : .venv/bin/python app/serveur/check.py [nom]"""
|
|
import json
|
|
import os
|
|
import shutil
|
|
import socket
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError
|
|
|
|
ICI = Path(__file__).resolve().parent
|
|
sys.path.insert(0, str(ICI))
|
|
import uvicorn # noqa: E402
|
|
import serveur # noqa: E402
|
|
import station # noqa: E402
|
|
|
|
|
|
def seance_temporaire():
|
|
return Path(tempfile.mkdtemp())
|
|
|
|
|
|
def check_serveur():
|
|
# le vrai serveur sur un port libre : la garde (Host, JSON déclaré), une lecture
|
|
with socket.socket() as so:
|
|
so.bind(("127.0.0.1", 0))
|
|
port = so.getsockname()[1]
|
|
srv = uvicorn.Server(uvicorn.Config(serveur.app, host="127.0.0.1", port=port, log_level="error"))
|
|
threading.Thread(target=srv.run, daemon=True).start()
|
|
while not srv.started:
|
|
time.sleep(0.05)
|
|
base = f"http://127.0.0.1:{port}"
|
|
|
|
def appel(chemin, corps=None, entetes=None, methode=None):
|
|
r = urllib.request.Request(base + chemin, json.dumps(corps).encode() if corps is not None else None,
|
|
{"Content-Type": "application/json", **(entetes or {})}, method=methode)
|
|
try:
|
|
with urllib.request.urlopen(r) as rep:
|
|
return rep.status
|
|
except HTTPError as e:
|
|
return e.code
|
|
try:
|
|
assert appel("/api/stations", entetes={"Host": "evil.example:80"}) == 403
|
|
assert appel("/api/etiquettes", {"station": "x"}, {"Content-Type": "text/plain"}) == 403
|
|
assert appel("/api/stations") == 200
|
|
assert appel("/api/analyses") == 200
|
|
assert appel("/api/analyses/INCONNUE/optimiser", {}) == 400
|
|
finally:
|
|
srv.should_exit = True
|
|
|
|
|
|
def leve(f, *a):
|
|
try:
|
|
f(*a)
|
|
except station.Refus as e:
|
|
return str(e)
|
|
raise AssertionError(f"{f.__name__}{a} n'a pas refusé")
|
|
|
|
|
|
def check_station():
|
|
# les données de la page Data, sur les vraies données ; les étiquettes dans un dossier temporaire
|
|
assert "NIEDERHORN" in station.stations()
|
|
im = station.images("NIEDERHORN", "2026-09-25", "2026-09-26")
|
|
assert im["images"] and im["positions"] and set(im["corr"]) == set(im["positions"]), list(im)
|
|
assert all(len(c) == len(im["images"]) for c in im["corr"].values())
|
|
assert station.image("NIEDERHORN", im["images"][0]["nom"]).is_file()
|
|
leve(station.image, "NIEDERHORN", "../../../.env")
|
|
leve(station.images, "../API", "", "")
|
|
assert station.images("LENZSPITZE", "2026-10-26", "2026-10-27")["images"]
|
|
c = station.courbes("LENZSPITZE", "2026-10-26", "2026-10-27")
|
|
titres = [p["titre"] for p in c["plots"]]
|
|
assert "Relative Corrected Vertical Shift" in titres and any(t.startswith("System: ") for t in titres), titres
|
|
ev = station.detecteurs("LENZSPITZE", "2026-10-26", "2026-10-27") # les détecteurs du journal, ~10 s
|
|
assert ev and {"debut", "fin", "categorie", "description", "capteurs"} <= set(ev[0]), ev[:1]
|
|
assert all(e["message"] and e["action"] and set(e["cibles"] + e["references"]) == set(e["capteurs"]) for e in ev), ev[:1]
|
|
assert station.message("A moved; nothing to do. The jump of 2 targets in this period has the same cause.") \
|
|
== "A moved. The jump of 2 targets in this period has the same cause."
|
|
assert all(e["fin"] >= "2026-10-26T00:00Z" and e["debut"] < "2026-10-27T00:00Z" for e in ev), [(e["debut"], e["fin"]) for e in ev]
|
|
assert not any("SIM_CCID" in t or t.startswith("System: ip") for t in titres)
|
|
assert all(len(c["T"][tr["t"]]) == len(tr["y"]) for p in c["plots"] for tr in p["traces"])
|
|
avant, station.ETIQUETTES = station.ETIQUETTES, seance_temporaire()
|
|
try:
|
|
e = station.ajouter({"station": "NIEDERHORN", "dossier": "auto", "debut": "2026-09-25T01:00Z",
|
|
"fin": "2026-09-25T02:00Z", "categorie": "Visibility", "description": "brouillard"})
|
|
assert e["id"] == "NIEDERHORN-1" and next(iter(e)) == "id", e
|
|
e2 = station.modifier({"station": "NIEDERHORN", "dossier": "auto", "avant": e,
|
|
"debut": e["debut"], "fin": e["fin"], "categorie": "", "description": "pluie"})
|
|
assert e2 == {"id": "NIEDERHORN-1", "debut": e["debut"], "fin": e["fin"], "description": "pluie"}, e2
|
|
assert station.lire("NIEDERHORN", "auto") == [e2]
|
|
assert "plus dans le fichier" in leve(station.supprimer, {"station": "NIEDERHORN", "dossier": "auto", "avant": e})
|
|
station.supprimer({"station": "NIEDERHORN", "dossier": "auto", "avant": e2})
|
|
assert station.lire("NIEDERHORN", "auto") == []
|
|
leve(station.ajouter, {"station": "NIEDERHORN", "dossier": "../x", "debut": "a", "fin": "b", "description": "x"})
|
|
leve(station.ajouter, {"station": "NIEDERHORN", "debut": "2026-09-25T02:00Z", "fin": "2026-09-25T01:00Z", "description": "x"})
|
|
finally:
|
|
shutil.rmtree(station.ETIQUETTES)
|
|
station.ETIQUETTES = avant
|
|
|
|
|
|
def check_optimisation():
|
|
# le bouton Optimiser (analyse.optimiser), sans claude : un faux processus qui ne finit que sur signal, une analyse finie
|
|
# copiée dans un dossier temporaire ; le verrou (une optimisation à la fois, ni analyse ni message pendant), l'état
|
|
# relu après un redémarrage
|
|
import analyse
|
|
fin = threading.Event()
|
|
|
|
lances = []
|
|
|
|
class FauxProcessus:
|
|
returncode = 0
|
|
stdout = iter(lambda: fin.wait() and "", "") # rien, jusqu'au signal
|
|
|
|
def __init__(self, args, *a, **k):
|
|
lances.append((args, k))
|
|
|
|
def wait(self):
|
|
return 0
|
|
|
|
avant = analyse.DOSSIER, analyse.subprocess.Popen, analyse.OPTIMIZER, analyse.SEANCES, analyse.AGENTS
|
|
cle = os.environ.get("ANTHROPIC_API_KEY")
|
|
os.environ["ANTHROPIC_API_KEY"] = "cle-de-test"
|
|
racine = seance_temporaire()
|
|
analyse.DOSSIER, analyse.OPTIMIZER, analyse.AGENTS = racine / "analyses", racine / "optimizer", racine / "agents"
|
|
analyse.SEANCES = analyse.OPTIMIZER / "seances"
|
|
analyse.subprocess.Popen = FauxProcessus
|
|
try:
|
|
for nom in ("NORDEND_a", "NORDEND_b"):
|
|
(analyse.DOSSIER / nom / "travail").mkdir(parents=True)
|
|
(analyse.DOSSIER / nom / "demande.json").write_text(json.dumps(
|
|
{"station": "NORDEND", "debut": "2026-11-04T21:12Z", "fin": "2026-11-07T14:12Z", "indices": ""}))
|
|
(analyse.DOSSIER / nom / "rapport.md").write_text("# rapport")
|
|
assert analyse.etat("NORDEND_a")["optimisation"] is None
|
|
# sans Optimizer, puis sans agents : un refus clair, pas une trace d'erreur
|
|
assert "optimizer/" in leve(analyse.optimiser, "NORDEND_a")
|
|
(analyse.OPTIMIZER / ".claude" / "skills" / "improve").mkdir(parents=True)
|
|
(analyse.OPTIMIZER / ".claude" / "skills" / "improve" / "SKILL.md").write_text("improve")
|
|
assert "agents/" in leve(analyse.optimiser, "NORDEND_a")
|
|
(analyse.AGENTS / ".claude-plugin").mkdir(parents=True)
|
|
(analyse.AGENTS / ".claude-plugin" / "plugin.json").write_text("{}")
|
|
assert "optimizer/" in leve(analyse.optimiser, "NORDEND_a") # sans les liens data, labeling, detectors d'Optimizer
|
|
for lien in ("data", "labeling", "detectors"):
|
|
(analyse.OPTIMIZER / lien).mkdir()
|
|
assert analyse.optimiser("NORDEND_a") == {}
|
|
assert analyse.etat("NORDEND_a")["optimisation"]["etat"] == "en cours"
|
|
leve(analyse.optimiser, "NORDEND_a")
|
|
leve(analyse.optimiser, "NORDEND_b")
|
|
leve(analyse.lancer, {"station": "NORDEND", "debut": "2026-11-04T00:00Z", "fin": "2026-11-05T00:00Z"})
|
|
leve(analyse.message, "NORDEND_b", {"texte": "continue"})
|
|
fin.set()
|
|
while analyse.etat("NORDEND_a")["optimisation"]["etat"] == "en cours":
|
|
time.sleep(0.05)
|
|
assert analyse.etat("NORDEND_a")["optimisation"]["etat"] == "fini"
|
|
args, k = lances[0] # /improve dans Optimizer, sur la plage de l'analyse, TO exclu
|
|
requete = args[2]
|
|
assert requete.startswith("/improve ") and "STATION: data/NORDEND. FROM: 2026-11-04. TO: 2026-11-08." in requete \
|
|
and "OUT: seances/NORDEND_a_" in requete, requete
|
|
assert k["cwd"] == analyse.OPTIMIZER.resolve() and "--plugin-dir" in args, (args, k)
|
|
assert all("ANTHROPIC_API_KEY" not in kw["env"] for _, kw in lances), "une clé d'API passe à claude"
|
|
# isolés des réglages du poste (plugins, hooks, serveurs MCP de l'utilisateur)
|
|
assert all(a[a.index("--setting-sources") + 1] == "project,local" and "--strict-mcp-config" in a for a, _ in lances)
|
|
args, k = lances[1] # puis le tool-builder du dépôt agents, sur le dépôt tools
|
|
assert args[args.index("--agent") + 1] == "agents:tool-builder" and "Outils : tools/" in args[2], args
|
|
analyse.analyses["NORDEND_b"]["etat"] = "en cours" # une analyse qui tourne bloque l'optimisation
|
|
leve(analyse.optimiser, "NORDEND_a")
|
|
# après un redémarrage : le flux finit par {"type": "fin"} -> fini ; sans cette ligne -> interrompue ; le bilan des
|
|
# détecteurs et celui des outils en une page
|
|
flux = analyse.DOSSIER / "NORDEND_a" / "travail" / "optimisation.jsonl"
|
|
assert flux.read_text().endswith('{"type": "fin", "etat": "fini"}\n'), flux.read_text()
|
|
analyse.analyses.clear()
|
|
analyse.optimisations.clear()
|
|
assert analyse.etat("NORDEND_a")["optimisation"]["etat"] == "fini"
|
|
flux.write_text('{"type": "assistant", "message": {"content": []}}\n')
|
|
analyse.optimisations.clear()
|
|
assert analyse.etat("NORDEND_a")["optimisation"]["etat"] == "interrompue"
|
|
(analyse.SEANCES / "NORDEND_a_20261113T1000Z").mkdir(parents=True)
|
|
(analyse.SEANCES / "NORDEND_a_20261113T1000Z" / "summary.md").write_text("# improve\n\n**Result**: none")
|
|
# une nouvelle analyse de la même plage (NORDEND_a_143000) : sa séance n'est pas le bilan de NORDEND_a
|
|
(analyse.SEANCES / "NORDEND_a_143000_20261113T1100Z").mkdir(parents=True)
|
|
(analyse.SEANCES / "NORDEND_a_143000_20261113T1100Z" / "summary.md").write_text("# autre analyse")
|
|
assert analyse._bilan("NORDEND_a").parent.name == "NORDEND_a_20261113T1000Z", analyse._bilan("NORDEND_a")
|
|
(analyse.DOSSIER / "NORDEND_a" / "outils.md").write_text("# Outils\n\n**Outils modifiés** : aucun")
|
|
assert analyse.etat("NORDEND_a")["optimisation"]["bilan"]
|
|
page = analyse.bilan("NORDEND_a", False)
|
|
assert "<strong>Result</strong>" in page and "<strong>Outils modifiés</strong>" in page, page
|
|
assert analyse.etat("NORDEND_b")["optimisation"] is None
|
|
finally:
|
|
fin.set()
|
|
os.environ.pop("ANTHROPIC_API_KEY")
|
|
if cle is not None:
|
|
os.environ["ANTHROPIC_API_KEY"] = cle
|
|
shutil.rmtree(racine)
|
|
analyse.DOSSIER, analyse.subprocess.Popen, analyse.OPTIMIZER, analyse.SEANCES, analyse.AGENTS = avant
|
|
analyse.analyses.clear()
|
|
analyse.optimisations.clear()
|
|
|
|
|
|
def check_analyse():
|
|
# « Analyser la plage » puis un message (analyse.lancer, analyse.message), sans claude : l'analyste du dépôt agents, ses
|
|
# paramètres, et la reprise de sa session avec le même agent
|
|
import analyse
|
|
lances = []
|
|
|
|
class FauxProcessus:
|
|
returncode = 0
|
|
|
|
def __init__(self, args, *a, **k):
|
|
lances.append((args, k))
|
|
self.stdout = iter([])
|
|
|
|
def wait(self):
|
|
return 0
|
|
|
|
(station.RACINE / "out").mkdir(exist_ok=True) # sous la racine : la demande cite le dossier de sortie par rapport à elle
|
|
avant = analyse.DOSSIER, analyse.subprocess.Popen, analyse.verser
|
|
analyse.DOSSIER = Path(tempfile.mkdtemp(dir=station.RACINE / "out"))
|
|
analyse.subprocess.Popen = FauxProcessus
|
|
analyse.verser = lambda *a: 0 # sinon le test réécrit le vrai labeling/auto/NORDEND.jsonl
|
|
cle = os.environ.get("ANTHROPIC_API_KEY")
|
|
os.environ["ANTHROPIC_API_KEY"] = "cle-de-test" # l'agent tourne sur l'abonnement, jamais sur une clé d'API
|
|
try:
|
|
nom = analyse.lancer({"station": "NORDEND", "debut": "2026-11-05T06:00Z", "fin": "2026-11-05T12:00Z"})["nom"]
|
|
while analyse.analyses[nom]["etat"] == "en cours":
|
|
time.sleep(0.05)
|
|
assert analyse.analyses[nom]["etat"] == "fini", analyse.analyses[nom]
|
|
args, k = lances[0]
|
|
assert args[args.index("--agent") + 1] == "agents:analyste" and "--plugin-dir" in args, args
|
|
assert "ANTHROPIC_API_KEY" not in k["env"] and "PATH" in k["env"], sorted(k.get("env") or {})
|
|
assert "DETECTEURS : non" in args[2] and "CONSIGNES : consignes/analyste.md" in args[2], args[2]
|
|
assert args[args.index("--setting-sources") + 1] == "project,local" and "--strict-mcp-config" in args, args
|
|
(analyse.DOSSIER / nom / "travail" / "session").write_text("s-1")
|
|
analyse.message(nom, {"texte": "continue"})
|
|
while analyse.analyses[nom]["etat"] == "en cours":
|
|
time.sleep(0.05)
|
|
args, k = lances[1]
|
|
assert "ANTHROPIC_API_KEY" not in k["env"], sorted(k.get("env") or {})
|
|
assert args[args.index("--resume") + 1] == "s-1" and args[args.index("--agent") + 1] == "agents:analyste" \
|
|
and "--plugin-dir" in args, args
|
|
agents, analyse.AGENTS = analyse.AGENTS, analyse.DOSSIER / "sans-agents" # le lien agents/ manque : refus clair
|
|
try:
|
|
assert "agents/" in leve(analyse.lancer, {"station": "NORDEND", "debut": "2026-11-06T06:00Z", "fin": "2026-11-06T12:00Z"})
|
|
finally:
|
|
analyse.AGENTS = agents
|
|
finally:
|
|
os.environ.pop("ANTHROPIC_API_KEY")
|
|
if cle is not None:
|
|
os.environ["ANTHROPIC_API_KEY"] = cle
|
|
shutil.rmtree(analyse.DOSSIER)
|
|
analyse.DOSSIER, analyse.subprocess.Popen, analyse.verser = avant
|
|
analyse.analyses.clear()
|
|
|
|
|
|
CHECKS = [check_serveur, check_station, check_optimisation, check_analyse]
|
|
|
|
if __name__ == "__main__":
|
|
nom = sys.argv[1] if len(sys.argv) > 1 else None
|
|
for f in CHECKS:
|
|
if nom in (None, f.__name__):
|
|
f()
|
|
print("ok", f.__name__)
|