P-0000: Register-Dienst (Minimalfassung) mit FastAPI und SQLite, Sendebefehl projekt_id.sh, Tests projekt2id.2 und .3

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-03 10:48:39 +01:00
parent 8453e77153
commit c7f33b46bc
12 changed files with 848 additions and 3 deletions

119
server/tests/projekt2id.py Normal file
View File

@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""Automatische Tests projekt2id.2 und .3 (Übergangsweg über skill/scripts/projekt_id.sh, bis es den Agenten gibt).
Startet einen echten Register-Dienst (run.py) auf 127.0.0.1 mit frischer Datenbank in einem Temp-Ordner und ruft
projekt_id.sh, init.sh und check_format.py auf. Aufruf (aus dem Projektordner): python3 server/tests/projekt2id.py
Ausgabe je Test `- id: ✓|✗ Notiz`, Exit-Code 1 wenn einer ✗ ist. Test .1 (Agent holt die ID nach) ist hier NICHT abgedeckt.
"""
import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
PY = os.path.join(ROOT, "server", ".venv", "bin", "python")
PID_SH = os.path.join(ROOT, "skill", "scripts", "projekt_id.sh")
INIT = os.path.join(ROOT, "skill", "scripts", "init.sh")
LINT = os.path.join(ROOT, "skill", "scripts", "check_format.py")
alle = []
def melde(tid, ok, notiz):
alle.append(ok)
print(f"- {tid}: {'✓' if ok else '✗'} {notiz}")
def freier_port():
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
def projekt(basis, name, remote):
d = os.path.join(basis, name)
os.makedirs(d)
subprocess.run(["git", "init", "-q", d], check=True)
subprocess.run(["git", "-C", d, "remote", "add", "origin", remote], check=True)
return d
def holen(url, pfad):
with urllib.request.urlopen(url + pfad, timeout=5) as r:
return json.loads(r.read())
def main():
basis = tempfile.mkdtemp(prefix="projekt2id-")
port = freier_port()
url = f"http://127.0.0.1:{port}"
env = dict(os.environ, REGISTER_PORT=str(port), REGISTER_BIND="127.0.0.1", REGISTER_DB=os.path.join(basis, "daten", "r.db"))
dienst = subprocess.Popen([PY, os.path.join(ROOT, "server", "run.py")], env=env, cwd=os.path.join(ROOT, "server"),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
try:
for _ in range(50):
try:
if holen(url, "/api/health").get("ok"):
break
except Exception:
time.sleep(0.1)
else:
print("Dienst startete nicht:", dienst.stdout.read() if dienst.poll() is not None else "keine Antwort")
sys.exit(1)
e = dict(os.environ, REGISTER_URL=url)
# .2 ID holen, Projekt mit init.sh anlegen, Register enthält Name und Git-Adresse
d1 = projekt(basis, "erstes", "ssh://git@git.example.org:2222/test/erstes.git")
p = subprocess.run(["bash", PID_SH, "Erstes Projekt", d1], env=dict(e, RECHNER="rechner-a"), capture_output=True, text=True)
pid = p.stdout.strip()
i = subprocess.run(["bash", INIT, "Erstes Projekt", d1, pid], capture_output=True, text=True)
l = subprocess.run([sys.executable, "-I", LINT, os.path.join(d1, "ROADMAP.md")], capture_output=True, text=True)
reg = {x["id"]: x for x in holen(url, "/api/projekte")}
ok = (p.returncode == 0 and pid == "P-0001" and i.returncode == 0 and l.returncode == 0 and f"Projekt-ID: {pid}" in l.stdout
and pid in reg and reg[pid]["name"] == "Erstes Projekt"
and reg[pid]["git_adresse"] == "git.example.org:2222/test/erstes" and reg[pid]["rechner"] == ["rechner-a"])
melde("projekt2id.2", ok, "nächste freie ID P-0001, init.sh legt Projekt an, Prüfskript OK, Register hat Name, Git-Adresse und Rechner"
if ok else f"Sendebefehl Exit {p.returncode} {p.stderr[-200:]!r}, ID {pid!r}, init {i.returncode}, lint {l.returncode} {l.stdout[-200:]!r}")
# .3 dasselbe Repo auf zweitem Rechner (andere Schreibweise der Adresse): vorhandene ID, keine neue
d2 = projekt(basis, "zweiter-rechner", "ssh://git@GIT.example.org:2222/test/erstes/")
p2 = subprocess.run(["bash", PID_SH, "Erstes Projekt", d2], env=dict(e, RECHNER="rechner-b"), capture_output=True, text=True)
d3 = projekt(basis, "anderes", "ssh://git@git.example.org:2222/test/anderes.git")
p3 = subprocess.run(["bash", PID_SH, "Anderes", d3], env=dict(e, RECHNER="rechner-b"), capture_output=True, text=True)
reg = {x["id"]: x for x in holen(url, "/api/projekte")}
ok = (p2.returncode == 0 and p2.stdout.strip() == pid and reg[pid]["rechner"] == ["rechner-a", "rechner-b"]
and p3.stdout.strip() == "P-0002" and len(reg) == 3)
melde("projekt2id.3", ok, "zweiter Rechner bekommt dieselbe ID P-0001 (Rechner a und b vermerkt), ein weiteres Projekt P-0002, im Register 3 Projekte"
if ok else f"zweiter Rechner: {p2.stdout.strip()!r} {p2.stderr[-200:]!r}, drittes: {p3.stdout.strip()!r}, Register: {list(reg)}")
# Zusatz: Dienst nicht erreichbar -> klare Meldung, Exit 1, keine ID
p4 = subprocess.run(["bash", PID_SH, "X", d1], env=dict(e, REGISTER_URL=f"http://127.0.0.1:{freier_port()}"), capture_output=True, text=True)
ok = p4.returncode == 1 and p4.stdout.strip() == "" and "nicht erreichbar" in p4.stderr and "offen" in p4.stderr
melde("projekt2id.2z", ok, "Dienst nicht erreichbar: Exit 1, keine ID, Hinweis auf 'offen'" if ok else f"Exit {p4.returncode}, {p4.stderr[-200:]!r}")
# Zusatz: Projekt ohne Remote origin -> Fehler, nichts wird vergeben
d5 = os.path.join(basis, "ohne-remote")
os.makedirs(d5)
subprocess.run(["git", "init", "-q", d5], check=True)
p5 = subprocess.run(["bash", PID_SH, "Y", d5], env=e, capture_output=True, text=True)
n_nachher = len(holen(url, "/api/projekte"))
ok = p5.returncode == 1 and "origin" in p5.stderr and n_nachher == 3
melde("projekt2id.2y", ok, "ohne Remote origin: Fehler, im Register nichts Neues" if ok else f"Exit {p5.returncode}, Register {n_nachher}")
finally:
dienst.terminate()
try:
dienst.wait(timeout=5)
except subprocess.TimeoutExpired:
dienst.kill()
shutil.rmtree(basis, ignore_errors=True)
sys.exit(0 if all(alle) else 1)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,136 @@
"""Einheiten- und Dienst-Tests des Registers (ohne Netz, mit eingebautem Testclient).
Aufruf (aus server/): .venv/bin/python -m unittest discover -s tests -v
"""
import os
import sqlite3
import sys
import tempfile
import threading
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from fastapi.testclient import TestClient # noqa: E402
from register.app import erzeuge_app # noqa: E402
from register.normalize import normalisiere # noqa: E402
import run # noqa: E402
P0 = "ssh://git@git.wlkns.org:2222/wlkns-dev/projekt-plattform.git"
def anfrage(c, name="X", git="ssh://git@git.example.org/a/b.git", rechner="r1"):
return c.post("/api/register", json={"name": name, "git_adresse": git, "rechner": rechner})
class Basis(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.db = os.path.join(self.tmp.name, "r.db")
self.c = TestClient(erzeuge_app(self.db))
def tearDown(self):
self.tmp.cleanup()
class TestNormalisieren(unittest.TestCase):
def test_schreibweisen(self):
a = normalisiere("ssh://git@git.wlkns.org:2222/wlkns-dev/projekt-plattform.git")
self.assertEqual(a, "git.wlkns.org:2222/wlkns-dev/projekt-plattform")
self.assertEqual(normalisiere("ssh://GIT@Git.WLKNS.org:2222/wlkns-dev/projekt-plattform/"), a)
self.assertEqual(normalisiere("git@host.x:o/r.git"), normalisiere("https://u@HOST.x/o/r"))
def test_ssh_und_https_sind_verschieden_wenn_der_port_abweicht(self):
self.assertNotEqual(normalisiere("ssh://git@h:2222/o/r.git"), normalisiere("https://h/o/r.git"))
def test_unlesbar(self):
for schlecht in ["", " ", "kein url", "https://nurhost"]:
with self.assertRaises(ValueError, msg=schlecht):
normalisiere(schlecht)
class TestRegister(Basis):
def test_seed_p0000(self):
r = anfrage(self.c, "Projekt-Plattform", P0, "pc1").json()
self.assertEqual((r["id"], r["neu"]), ("P-0000", False))
def test_neue_ids_fortlaufend(self):
ids = [anfrage(self.c, f"p{i}", f"ssh://git@h/o/r{i}.git").json()["id"] for i in range(3)]
self.assertEqual(ids, ["P-0001", "P-0002", "P-0003"])
def test_bekannte_adresse_gleiche_id_anderer_rechner(self):
a = anfrage(self.c, "X", "ssh://git@h/o/r.git", "pc1").json()
# scp-Schreibweise und ssh:// ohne Port sind dieselbe Adresse (h/o/r)
b = anfrage(self.c, "X", "git@h:o/r.git", "pc2").json()
self.assertTrue(a["neu"])
self.assertEqual((b["id"], b["neu"]), (a["id"], False))
rechner = [p for p in self.c.get("/api/projekte").json() if p["id"] == a["id"]][0]["rechner"]
self.assertEqual(rechner, ["pc1", "pc2"])
def test_gleicher_host_anderer_port_ist_anderes_projekt(self):
a = anfrage(self.c, "X", "ssh://git@h:2222/o/r.git").json()
b = anfrage(self.c, "X", "https://h/o/r.git").json()
self.assertNotEqual(a["id"], b["id"])
def test_namensabweichung_warnt_aendert_nichts(self):
anfrage(self.c, "Alt", "ssh://git@h/o/r.git")
r = anfrage(self.c, "Neu", "ssh://git@h/o/r.git").json()
self.assertEqual(r["name"], "Alt")
self.assertTrue(r["warnungen"])
def test_nummern_nie_wiederverwenden(self):
anfrage(self.c, "A", "ssh://git@h/o/a.git") # P-0001
con = sqlite3.connect(self.db)
con.execute("DELETE FROM rechner WHERE projekt_id = 'P-0001'")
con.execute("DELETE FROM projekte WHERE id = 'P-0001'")
con.commit()
con.close()
self.assertEqual(anfrage(self.c, "B", "ssh://git@h/o/b.git").json()["id"], "P-0002")
def test_zaehler_ueberlebt_neustart(self):
anfrage(self.c, "A", "ssh://git@h/o/a.git")
c2 = TestClient(erzeuge_app(self.db)) # zweite Anwendung auf derselben Datei
self.assertEqual(anfrage(c2, "B", "ssh://git@h/o/b.git").json()["id"], "P-0002")
self.assertEqual(anfrage(c2, "A", "ssh://git@h/o/a.git").json()["id"], "P-0001")
def test_ungueltige_eingaben(self):
self.assertEqual(anfrage(self.c, "", "ssh://git@h/o/r.git").status_code, 422)
self.assertEqual(anfrage(self.c, "X", "keine adresse").status_code, 422)
self.assertEqual(self.c.post("/api/register", json={"name": "X"}).status_code, 422)
self.assertEqual(len(self.c.get("/api/projekte").json()), 1) # nur der Seed
def test_gleichzeitige_anfragen_ergeben_verschiedene_ids(self):
ergebnis, fehler = [], []
def los(i):
try:
ergebnis.append(anfrage(self.c, f"p{i}", f"ssh://git@h/o/r{i}.git").json()["id"])
except Exception as e: # pragma: no cover
fehler.append(e)
ts = [threading.Thread(target=los, args=(i,)) for i in range(20)]
[t.start() for t in ts]
[t.join() for t in ts]
self.assertEqual(fehler, [])
self.assertEqual(len(set(ergebnis)), 20)
def test_keine_schreibenden_wege_ausser_register(self):
for pfad in ["/api/projekte", "/api/register", "/api/health"]:
self.assertEqual(self.c.delete(pfad).status_code, 405)
self.assertEqual(self.c.get("/docs").status_code, 404)
class TestAdressen(unittest.TestCase):
def test_erlaubt(self):
self.assertEqual(run.adressen("127.0.0.1, 192.168.13.64"), ["127.0.0.1", "192.168.13.64"])
self.assertEqual(run.adressen("10.0.0.2"), ["10.0.0.2"])
def test_abgelehnt(self):
for schlecht in ["0.0.0.0", "::", "100.69.190.27", "100.64.0.1", "8.8.8.8", "kein-host", ""]:
with self.assertRaises(ValueError, msg=schlecht):
run.adressen(schlecht)
if __name__ == "__main__":
unittest.main()