import importlib import time import pytest server_app_module = importlib.import_module("server.app") # Expose app and init_db from the imported module app = server_app_module.app init_db = server_app_module.init_db @pytest.fixture(autouse=True) def setup_tmp_db(tmp_path, monkeypatch): tmp_db = tmp_path / "forms.db" monkeypatch.setattr(server_app_module, "DB_PATH", tmp_db, raising=False) init_db() yield @pytest.fixture def client(): with app.test_client() as client: yield client def test_metrics_endpoint_reports_uptime_and_total(client): # Ensure a simple GET to /metrics succeeds and returns recent uptime resp = client.get("/metrics") assert resp.status_code == 200 # If prometheus_client isn't installed, metrics returns JSON if resp.content_type.startswith("application/json"): body = resp.get_json() assert "uptime_seconds" in body assert "total_submissions" in body else: # If prometheus_client is present, the response is the Prometheus text format text = resp.get_data(as_text=True) assert "# HELP" in text or "http_request_duration_seconds" in text def test_request_metrics_increment_on_request(client): # Make sure we have a baseline before = client.get("/metrics").get_data(as_text=True) # Trigger a contact submission attempt (invalid payload will still count the request) client.post("/api/contact", data={}) # Wait a tiny bit for histogram observation time.sleep(0.01) after = client.get("/metrics").get_data(as_text=True) # If prometheus_client isn't present, the JSON will include total_submissions if client.get("/metrics").content_type.startswith("application/json"): before_json = client.get("/metrics").get_json() after_json = client.get("/metrics").get_json() assert after_json["uptime_seconds"] >= before_json["uptime_seconds"] else: # Ensure some metrics text exists and that it changed (best-effort) assert after != before