Message: the first sentence of the journal phrase; action: the client column of labeling/familles.md, refined per sort. The hover shows the targets only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
151 lines
7.9 KiB
Python
151 lines
7.9 KiB
Python
"""Vérifications de la web app, sans appel à l'API (faux client) : API/.venv/bin/python app/serveur/check.py [nom]"""
|
|
import json
|
|
import shutil
|
|
import socket
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError
|
|
|
|
ICI = Path(__file__).resolve().parent
|
|
sys.path[:0] = [str(ICI), str(ICI.parents[1] / "API" / "support")]
|
|
import uvicorn # noqa: E402
|
|
import seance # noqa: E402
|
|
import serveur # noqa: E402
|
|
import station # noqa: E402
|
|
from check import Bloc, FauxClient, reponse, seance_temporaire # noqa: E402 (les faux de API/support/check.py)
|
|
|
|
|
|
def check_serveur():
|
|
# le vrai serveur sur un port libre, une séance au faux client : la garde, l'analyse, le flux, le PDF absent
|
|
with socket.socket() as so:
|
|
so.bind(("127.0.0.1", 0))
|
|
port = so.getsockname()[1]
|
|
cases = seance.CASES
|
|
seance.CASES, serveur.CLIENT = seance_temporaire(), FauxClient(reponse([Bloc(type="text", text="Bonjour Marc")], "end_turn"))
|
|
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):
|
|
r = urllib.request.Request(base + chemin, json.dumps(corps).encode() if corps is not None else None,
|
|
{"Content-Type": "application/json", **(entetes or {})})
|
|
try:
|
|
with urllib.request.urlopen(r) as rep:
|
|
return rep.status
|
|
except HTTPError as e:
|
|
return e.code
|
|
try:
|
|
assert appel("/api/pdf", entetes={"Host": "evil.example:80"}) == 403
|
|
assert appel("/api/analyser", {"mail": "x"}, {"Content-Type": "text/plain"}) == 403
|
|
assert appel("/api/analyser", {"mail": " "}) == 400
|
|
assert appel("/api/analyser", {"mail": "Bonjour", "contexte": "", "images": []}) == 200
|
|
with urllib.request.urlopen(base + "/api/flux", timeout=10) as f:
|
|
premier, textes = None, []
|
|
for ligne in f:
|
|
if ligne.startswith(b"data: "):
|
|
m = json.loads(ligne[6:])
|
|
premier = premier or m
|
|
textes += [e["texte"] for e in m["evenements"]]
|
|
if "Bonjour Marc" in textes and not m["occupe"]["support"]:
|
|
break
|
|
assert premier["depuis"] == 0 and premier["id"], premier
|
|
assert appel("/api/pdf") == 404
|
|
(serveur.etat["seance"].dossier / "v1.pdf").write_bytes(b"%PDF-1.4")
|
|
with urllib.request.urlopen(base + "/api/pdf") as rep:
|
|
assert rep.read() == b"%PDF-1.4" and rep.headers["Content-Disposition"].startswith("inline"), rep.headers
|
|
finally:
|
|
srv.should_exit = True
|
|
shutil.rmtree(seance.CASES)
|
|
seance.CASES = cases
|
|
|
|
|
|
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_libredesk():
|
|
# le fil et ses images depuis de fausses réponses de l'API : ordre, notes privées, logos écartés
|
|
import base64
|
|
import libredesk
|
|
png = b"\x89PNG" + b"x" * libredesk.TAILLE_MIN
|
|
msgs = [{"created_at": "2026-11-04T08:00Z", "type": "incoming", "private": False, "text_content": "Bonjour, trou ?",
|
|
"author": {"first_name": "David", "email": "d@x.ch"}, "meta": {"subject": "Crissier"},
|
|
"attachments": [{"name": "c.png", "content_type": "image/png", "size": len(png), "url": "/uploads/a"},
|
|
{"name": "logo.png", "content_type": "image/png", "size": 900, "url": "/uploads/b"}]},
|
|
{"created_at": "2026-11-04T09:00Z", "type": "outgoing", "private": True, "text_content": "note interne"},
|
|
{"created_at": "2026-11-05T08:00Z", "type": "outgoing", "private": False, "text_content": "Hello David",
|
|
"author": {"first_name": "Marc"}}]
|
|
avant = libredesk._requete
|
|
libredesk._requete = lambda c: json.dumps({"data": {"results": msgs}}).encode() if "/messages" in c else png
|
|
try:
|
|
c = libredesk.conversation("0b1c-2d")
|
|
finally:
|
|
libredesk._requete = avant
|
|
assert c["mail"].index("Hello David") < c["mail"].index("Bonjour, trou ?") and "note interne" not in c["mail"], c["mail"]
|
|
assert "De: David <d@x.ch>" in c["mail"] and "Objet: Crissier" in c["mail"], c["mail"]
|
|
assert [i["nom"] for i in c["images"]] == ["c.png"] and base64.b64decode(c["images"][0]["base64"]) == png
|
|
try:
|
|
libredesk.conversation("../x")
|
|
raise AssertionError("uuid ../x accepté")
|
|
except ValueError:
|
|
pass
|
|
|
|
|
|
CHECKS = [check_serveur, check_station, check_libredesk]
|
|
|
|
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__)
|