162 lines
4.9 KiB
Python
162 lines
4.9 KiB
Python
"""Test setup: separate PostgreSQL database + temporary upload dir.
|
|
|
|
The watermark logo used here is a generated TEST FIXTURE only (a plain shape),
|
|
written to a temp dir. It is never used by the running application.
|
|
"""
|
|
|
|
import asyncio
|
|
import io
|
|
import os
|
|
import shutil
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
from dotenv import dotenv_values
|
|
from PIL import Image, ImageDraw
|
|
|
|
BACKEND_DIR = Path(__file__).resolve().parents[1]
|
|
_env = dotenv_values(BACKEND_DIR / ".env")
|
|
TEST_DB_URL = os.environ.get("TEST_DATABASE_URL") or _env.get("TEST_DATABASE_URL")
|
|
if not TEST_DB_URL:
|
|
raise RuntimeError("Set TEST_DATABASE_URL (see backend/.env.example)")
|
|
if not TEST_DB_URL.rsplit("/", 1)[-1].endswith("_test"):
|
|
raise RuntimeError("Refusing to run tests against a database whose name does not end in _test")
|
|
|
|
TMP_ROOT = Path(tempfile.mkdtemp(prefix="saurashakti-tests-"))
|
|
LOGO_PATH = TMP_ROOT / "fixture-logo.png"
|
|
|
|
os.environ.update(
|
|
{
|
|
"ENVIRONMENT": "test",
|
|
"DATABASE_URL": TEST_DB_URL,
|
|
"UPLOAD_DIR": str(TMP_ROOT / "uploads"),
|
|
"WATERMARK_LOGO_PATH": str(LOGO_PATH),
|
|
"MEDIA_BASE_URL": "http://testserver/media",
|
|
"LOGIN_RATE_LIMIT_PER_MINUTE": "5",
|
|
"PUBLIC_FORM_RATE_LIMIT_PER_MINUTE": "50",
|
|
}
|
|
)
|
|
|
|
|
|
def _make_fixture_logo() -> None:
|
|
# 400x120 transparent PNG: white rounded bar with orange dot (wide aspect, like a wordmark)
|
|
logo = Image.new("RGBA", (400, 120), (0, 0, 0, 0))
|
|
d = ImageDraw.Draw(logo)
|
|
d.rounded_rectangle((0, 20, 400, 100), radius=30, fill=(255, 255, 255, 255))
|
|
d.ellipse((20, 30, 80, 90), fill=(245, 130, 32, 255))
|
|
logo.save(LOGO_PATH)
|
|
|
|
|
|
_make_fixture_logo()
|
|
|
|
import pytest # noqa: E402
|
|
from httpx import ASGITransport, AsyncClient # noqa: E402
|
|
from sqlalchemy import text # noqa: E402
|
|
|
|
from app.core.database import SessionLocal, engine # noqa: E402
|
|
from app.core.security import hash_password # noqa: E402
|
|
from app.main import app # noqa: E402
|
|
from app.middleware.rate_limit import reset_all_limiters # noqa: E402
|
|
from app.models import Admin, AdminRole, Base # noqa: E402
|
|
|
|
PASSWORD = "TestPassw0rd!"
|
|
|
|
|
|
@pytest.fixture(scope="session", autouse=True)
|
|
def _schema():
|
|
async def create():
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.drop_all)
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
async def drop():
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.drop_all)
|
|
|
|
asyncio.run(create())
|
|
yield
|
|
asyncio.run(drop())
|
|
shutil.rmtree(TMP_ROOT, ignore_errors=True)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
async def _clean_state():
|
|
reset_all_limiters()
|
|
yield
|
|
tables = ", ".join(t.name for t in Base.metadata.sorted_tables)
|
|
async with engine.begin() as conn:
|
|
await conn.execute(text(f"TRUNCATE {tables} RESTART IDENTITY CASCADE"))
|
|
uploads = TMP_ROOT / "uploads"
|
|
for sub in ("originals", "watermarked", "thumbnails"):
|
|
for f in (uploads / sub).glob("*"):
|
|
f.unlink()
|
|
|
|
|
|
@pytest.fixture
|
|
async def client():
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver") as c:
|
|
yield c
|
|
|
|
|
|
async def _create_admin(email: str, role: AdminRole, active: bool = True) -> Admin:
|
|
async with SessionLocal() as db:
|
|
admin = Admin(
|
|
email=email,
|
|
full_name=email.split("@")[0].title(),
|
|
hashed_password=hash_password(PASSWORD),
|
|
role=role,
|
|
is_active=active,
|
|
)
|
|
db.add(admin)
|
|
await db.commit()
|
|
await db.refresh(admin)
|
|
return admin
|
|
|
|
|
|
async def _token(client, email: str) -> dict[str, str]:
|
|
r = await client.post("/api/auth/login", json={"email": email, "password": PASSWORD})
|
|
assert r.status_code == 200, r.text
|
|
return {"Authorization": f"Bearer {r.json()['access_token']}"}
|
|
|
|
|
|
@pytest.fixture
|
|
async def super_headers(client):
|
|
await _create_admin("owner@example.com", AdminRole.SUPER_ADMIN)
|
|
return await _token(client, "owner@example.com")
|
|
|
|
|
|
@pytest.fixture
|
|
async def admin_headers(client):
|
|
await _create_admin("admin@example.com", AdminRole.ADMIN)
|
|
return await _token(client, "admin@example.com")
|
|
|
|
|
|
@pytest.fixture
|
|
async def editor_headers(client):
|
|
await _create_admin("editor@example.com", AdminRole.EDITOR)
|
|
return await _token(client, "editor@example.com")
|
|
|
|
|
|
@pytest.fixture
|
|
def create_admin():
|
|
return _create_admin
|
|
|
|
|
|
@pytest.fixture
|
|
def upload_dir() -> Path:
|
|
return TMP_ROOT / "uploads"
|
|
|
|
|
|
@pytest.fixture
|
|
def logo_path() -> Path:
|
|
return LOGO_PATH
|
|
|
|
|
|
def make_image(fmt: str, size=(1600, 1000), color=(30, 90, 160), mode="RGB", **save_kw) -> bytes:
|
|
img = Image.new(mode, size, color if mode == "RGB" else (*color, 255))
|
|
# some structure so it isn't a flat colour
|
|
ImageDraw.Draw(img).rectangle((0, 0, size[0] // 2, size[1] // 2), fill=(200, 200, 40))
|
|
buf = io.BytesIO()
|
|
img.save(buf, fmt, **save_kw)
|
|
return buf.getvalue()
|