import os import tempfile import threading import time # The DB path must be set before database.py is imported (via main) _tmp = tempfile.TemporaryDirectory() os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db") from fastapi.testclient import TestClient from main import app from services import pki from utils.auth import verify_token app.dependency_overrides[verify_token] = lambda: {"sub": "test"} client = TestClient(app) def test_async_init_runs_once(monkeypatch): pki_dir = os.path.join(_tmp.name, "pki") release = threading.Event() def touch(*parts): path = os.path.join(pki_dir, *parts) os.makedirs(os.path.dirname(path), exist_ok=True) open(path, "w").close() def fake_easyrsa(command, env): if command[0] == "build-server-full": touch("issued", command[1] + ".crt") elif command[0] == "gen-dh": release.wait(5) # keeps the job running until the test lets go touch("dh.pem") elif command[0] == "gen-crl": touch("crl.pem") elif "build-ca" in command: touch("ca.crt") monkeypatch.setattr(pki, "PKI_DIR", pki_dir) monkeypatch.setattr(pki, "_run_easyrsa", fake_easyrsa) monkeypatch.setattr(pki, "_gen_ta_key", lambda: touch("ta.key")) monkeypatch.setattr(pki, "_publish_crl", lambda: True) res = client.post("/api/system/init") assert res.status_code == 202 and res.json() == {"state": "running"} assert client.post("/api/system/init").status_code == 409 assert client.get("/api/system/init/status").json()["state"] == "running" assert client.delete("/api/system/pki").status_code == 409 release.set() deadline = time.time() + 5 while time.time() < deadline: status = client.get("/api/system/init/status").json() if status["state"] != "running": break time.sleep(0.05) assert status["state"] == "done" and status["initialized"] is True assert client.post("/api/system/init").status_code == 409