complycore/backend/tests/test_api.py

94 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# backend/tests/test_api.py
"""
Simple smoketest suite for the ComplyCore FastAPI backend.
Run with:
poetry install --with dev # or `pip install -r requirements-dev.txt`
pytest backend/tests # or simply `pytest` at repo root
"""
import os
from datetime import datetime, timedelta, timezone
import jwt # PyJWT
import pytest
from fastapi.testclient import TestClient
# ---- local import of your FastAPI app ---------------------------------------
from backend.main import app # adjusts if your main.py lives elsewhere
# -----------------------------------------------------------------------------
client = TestClient(app)
# --------------------------------------------------------------------------- #
# Helpers #
# --------------------------------------------------------------------------- #
def make_test_jwt(
user_id: str = "00000000-0000-0000-0000-000000000002",
email: str = "testuser@complycore.dev",
role: str = "authenticated",
) -> str:
"""
Craft a short-lived JWT signed with the same secret the API expects.
"""
secret = os.getenv("SUPABASE_JWT_SECRET", "NOT_SET")
if secret == "NOT_SET":
raise RuntimeError(
"SUPABASE_JWT_SECRET not loaded copy backend/.env.example → "
".env and set your secret before running the tests"
)
now = datetime.now(timezone.utc)
payload = {
"sub": user_id,
"aud": "authenticated",
"role": role,
"email": email,
"iat": int(now.timestamp()),
"exp": int((now + timedelta(minutes=10)).timestamp()),
"iss": "supabase",
"email_confirmed_at": now.isoformat(),
}
return jwt.encode(payload, secret, algorithm="HS256")
# --------------------------------------------------------------------------- #
# Tests #
# --------------------------------------------------------------------------- #
def test_healthz():
r = client.get("/healthz")
assert r.status_code == 200
assert r.json() == {"status": "ok"}
@pytest.mark.skipif(
os.getenv("CI") == "true",
reason="Requires network access to Supabase; skip on CI",
)
def test_supabase_check():
"""
Only a connectivity smoke test we dont assert DB/user values because
those differ per environment, we just ensure *something* comes back.
"""
r = client.get("/supabase-check")
assert r.status_code == 200
body = r.json()
assert body.get("status") == "connected"
assert "db" in body and "user" in body
def test_me_authorized():
token = make_test_jwt()
r = client.get("/me", headers={"Authorization": f"Bearer {token}"})
assert r.status_code == 200
body = r.json()
assert body["id"] == "00000000-0000-0000-0000-000000000002"
assert body["email"] == "testuser@complycore.dev"
assert body["role"] == "authenticated"
def test_me_unauthorized():
r = client.get("/me") # no token
assert r.status_code == 401