-
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,142 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import jwt
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models import AdminRole
|
||||
from tests.conftest import PASSWORD
|
||||
|
||||
|
||||
async def test_health(client):
|
||||
r = await client.get("/api/health")
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["status"] == "ok" and body["database"] == "ok"
|
||||
assert body["watermark_logo_present"] is True
|
||||
|
||||
|
||||
async def test_login_success_and_me(client, create_admin):
|
||||
await create_admin("Owner@Example.com".lower(), AdminRole.SUPER_ADMIN)
|
||||
r = await client.post("/api/auth/login", json={"email": "OWNER@example.com", "password": PASSWORD})
|
||||
assert r.status_code == 200
|
||||
data = r.json()
|
||||
assert data["token_type"] == "bearer" and data["expires_in"] > 0
|
||||
assert "hashed_password" not in data["admin"]
|
||||
|
||||
me = await client.get("/api/auth/me", headers={"Authorization": f"Bearer {data['access_token']}"})
|
||||
assert me.status_code == 200
|
||||
assert me.json()["email"] == "owner@example.com"
|
||||
assert me.json()["last_login_at"] is not None
|
||||
|
||||
|
||||
async def test_login_wrong_password_and_unknown_email(client, create_admin):
|
||||
await create_admin("a@example.com", AdminRole.ADMIN)
|
||||
r1 = await client.post("/api/auth/login", json={"email": "a@example.com", "password": "nope"})
|
||||
r2 = await client.post("/api/auth/login", json={"email": "ghost@example.com", "password": "nope"})
|
||||
assert r1.status_code == r2.status_code == 401
|
||||
assert r1.json()["detail"] == r2.json()["detail"] # no user enumeration
|
||||
|
||||
|
||||
async def test_disabled_account_cannot_login(client, create_admin):
|
||||
await create_admin("off@example.com", AdminRole.ADMIN, active=False)
|
||||
r = await client.post("/api/auth/login", json={"email": "off@example.com", "password": PASSWORD})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
async def test_admin_routes_require_token(client):
|
||||
for method, url in [
|
||||
("get", "/api/auth/me"),
|
||||
("get", "/api/admin/enquiries"),
|
||||
("get", "/api/admin/dashboard/stats"),
|
||||
("post", "/api/admin/projects"),
|
||||
("post", "/api/admin/projects/1/images"),
|
||||
("delete", "/api/admin/project-images/1"),
|
||||
("post", "/api/admin/services"),
|
||||
("put", "/api/admin/content/hero"),
|
||||
]:
|
||||
r = await getattr(client, method)(url)
|
||||
assert r.status_code == 401, (method, url, r.status_code)
|
||||
|
||||
|
||||
async def test_invalid_and_expired_tokens(client, create_admin):
|
||||
admin = await create_admin("t@example.com", AdminRole.ADMIN)
|
||||
r = await client.get("/api/auth/me", headers={"Authorization": "Bearer not-a-jwt"})
|
||||
assert r.status_code == 401
|
||||
|
||||
forged = jwt.encode({"sub": str(admin.id), "type": "access", "iat": datetime.now(UTC),
|
||||
"exp": datetime.now(UTC) + timedelta(hours=1)}, "x" * 40, algorithm="HS256")
|
||||
r = await client.get("/api/auth/me", headers={"Authorization": f"Bearer {forged}"})
|
||||
assert r.status_code == 401
|
||||
|
||||
past = datetime.now(UTC) - timedelta(hours=2)
|
||||
expired = jwt.encode({"sub": str(admin.id), "type": "access", "iat": past,
|
||||
"exp": past + timedelta(minutes=1)}, settings.JWT_SECRET_KEY, algorithm="HS256")
|
||||
r = await client.get("/api/auth/me", headers={"Authorization": f"Bearer {expired}"})
|
||||
assert r.status_code == 401
|
||||
assert "expired" in r.json()["detail"].lower()
|
||||
|
||||
|
||||
async def test_login_rate_limited(client):
|
||||
codes = [
|
||||
(await client.post("/api/auth/login", json={"email": "x@example.com", "password": "bad"})).status_code
|
||||
for _ in range(6)
|
||||
]
|
||||
assert codes[:5] == [401] * 5
|
||||
assert codes[5] == 429
|
||||
|
||||
|
||||
async def test_role_based_access(client, editor_headers, admin_headers):
|
||||
# create an enquiry publicly
|
||||
await client.post("/api/enquiries", json={"name": "Ravi", "phone": "9876543210"})
|
||||
# editor can read but not delete enquiries
|
||||
assert (await client.get("/api/admin/enquiries", headers=editor_headers)).status_code == 200
|
||||
assert (await client.delete("/api/admin/enquiries/1", headers=editor_headers)).status_code == 403
|
||||
assert (await client.delete("/api/admin/enquiries/1", headers=admin_headers)).status_code == 204
|
||||
# only super admins manage admin accounts
|
||||
assert (await client.get("/api/admin/users", headers=admin_headers)).status_code == 403
|
||||
|
||||
|
||||
async def test_super_admin_manages_users(client, super_headers):
|
||||
r = await client.post(
|
||||
"/api/admin/users",
|
||||
headers=super_headers,
|
||||
json={"email": "New@Example.com", "full_name": "New Person", "password": "weak", "role": "editor"},
|
||||
)
|
||||
assert r.status_code == 422
|
||||
r = await client.post(
|
||||
"/api/admin/users",
|
||||
headers=super_headers,
|
||||
json={"email": "New@Example.com", "full_name": "New Person", "password": "Str0ngEnough", "role": "editor"},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
assert r.json()["email"] == "new@example.com"
|
||||
dup = await client.post(
|
||||
"/api/admin/users",
|
||||
headers=super_headers,
|
||||
json={"email": "new@example.com", "full_name": "Dup", "password": "Str0ngEnough"},
|
||||
)
|
||||
assert dup.status_code == 409
|
||||
|
||||
uid = r.json()["id"]
|
||||
r = await client.patch(f"/api/admin/users/{uid}", headers=super_headers, json={"is_active": False})
|
||||
assert r.status_code == 200 and r.json()["is_active"] is False
|
||||
me = (await client.get("/api/auth/me", headers=super_headers)).json()
|
||||
r = await client.patch(f"/api/admin/users/{me['id']}", headers=super_headers, json={"is_active": False})
|
||||
assert r.status_code == 400 # cannot lock yourself out
|
||||
|
||||
|
||||
async def test_change_password(client, admin_headers):
|
||||
r = await client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=admin_headers,
|
||||
json={"current_password": "wrong", "new_password": "An0therPassword"},
|
||||
)
|
||||
assert r.status_code == 400
|
||||
r = await client.post(
|
||||
"/api/auth/change-password",
|
||||
headers=admin_headers,
|
||||
json={"current_password": PASSWORD, "new_password": "An0therPassword"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
r = await client.post("/api/auth/login", json={"email": "admin@example.com", "password": "An0therPassword"})
|
||||
assert r.status_code == 200
|
||||
@@ -0,0 +1,143 @@
|
||||
VALID = {
|
||||
"name": "Priya Sharma",
|
||||
"phone": "+91 98765-43210",
|
||||
"email": "priya@example.com",
|
||||
"city": "Bhubaneswar",
|
||||
"property_type": "residential",
|
||||
"monthly_bill": 3500,
|
||||
"required_capacity_kw": 5,
|
||||
"message": "Need rooftop solar for my house.",
|
||||
}
|
||||
|
||||
|
||||
async def test_enquiry_submit_and_validation(client, admin_headers):
|
||||
r = await client.post("/api/enquiries", json=VALID)
|
||||
assert r.status_code == 201
|
||||
assert r.json()["success"] is True
|
||||
assert "id" not in r.json() # public response doesn't leak ids
|
||||
|
||||
bad = await client.post("/api/enquiries", json={"name": "A", "phone": "abc", "email": "nope"})
|
||||
assert bad.status_code == 422
|
||||
fields = {e["field"] for e in bad.json()["errors"]}
|
||||
assert {"name", "phone", "email"} <= fields
|
||||
|
||||
extra = await client.post("/api/enquiries", json={**VALID, "status": "converted"})
|
||||
assert extra.status_code == 422 # clients cannot set status
|
||||
|
||||
lst = (await client.get("/api/admin/enquiries", headers=admin_headers)).json()
|
||||
assert lst["total"] == 1
|
||||
item = lst["items"][0]
|
||||
assert item["phone"] == "+919876543210" # normalised
|
||||
assert item["status"] == "new"
|
||||
|
||||
|
||||
async def test_enquiry_honeypot_not_saved(client, admin_headers):
|
||||
r = await client.post("/api/enquiries", json={**VALID, "website": "http://spam.example"})
|
||||
assert r.status_code == 201
|
||||
assert (await client.get("/api/admin/enquiries", headers=admin_headers)).json()["total"] == 0
|
||||
|
||||
|
||||
async def test_enquiry_admin_workflow(client, admin_headers):
|
||||
for i, city in enumerate(["Cuttack", "Puri", "Cuttack"]):
|
||||
await client.post("/api/enquiries", json={**VALID, "name": f"Customer {i}", "city": city})
|
||||
|
||||
r = await client.get("/api/admin/enquiries", params={"search": "cuttack"}, headers=admin_headers)
|
||||
assert r.json()["total"] == 2
|
||||
r = await client.get("/api/admin/enquiries", params={"search": "100%_"}, headers=admin_headers)
|
||||
assert r.json()["total"] == 0 # LIKE wildcards are escaped
|
||||
|
||||
r = await client.patch(
|
||||
"/api/admin/enquiries/1",
|
||||
headers=admin_headers,
|
||||
json={"status": "site_visit_scheduled", "note": "Visit booked for Monday 11am"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["status"] == "site_visit_scheduled"
|
||||
assert body["notes"][0]["content"] == "Visit booked for Monday 11am"
|
||||
assert body["notes"][0]["author_name"] == "Admin"
|
||||
|
||||
r = await client.patch("/api/admin/enquiries/1", headers=admin_headers, json={"status": "bogus"})
|
||||
assert r.status_code == 422
|
||||
r = await client.patch("/api/admin/enquiries/1", headers=admin_headers, json={})
|
||||
assert r.status_code == 422
|
||||
|
||||
r = await client.get("/api/admin/enquiries", params={"status": "site_visit_scheduled"}, headers=admin_headers)
|
||||
assert r.json()["total"] == 1
|
||||
|
||||
detail = (await client.get("/api/admin/enquiries/1", headers=admin_headers)).json()
|
||||
assert detail["monthly_bill"] == 3500 and detail["message"]
|
||||
|
||||
stats = (await client.get("/api/admin/dashboard/stats", headers=admin_headers)).json()
|
||||
assert stats["total_enquiries"] == 3
|
||||
assert stats["new_enquiries"] == 2
|
||||
assert stats["site_visits_scheduled"] == 1
|
||||
assert len(stats["recent_enquiries"]) == 3
|
||||
|
||||
assert (await client.delete("/api/admin/enquiries/1", headers=admin_headers)).status_code == 204
|
||||
assert (await client.get("/api/admin/enquiries/1", headers=admin_headers)).status_code == 404
|
||||
assert (await client.delete("/api/admin/enquiries/999", headers=admin_headers)).status_code == 404
|
||||
|
||||
|
||||
async def test_contact_messages(client, admin_headers):
|
||||
r = await client.post("/api/contact", json={"name": "Asha", "email": "asha@example.com", "message": "Hello there"})
|
||||
assert r.status_code == 201
|
||||
bad = await client.post("/api/contact", json={"name": "Asha", "email": "bad", "message": "hi"})
|
||||
assert bad.status_code == 422
|
||||
lst = (await client.get("/api/admin/contact-messages", headers=admin_headers)).json()
|
||||
assert lst["total"] == 1 and lst["items"][0]["is_read"] is False
|
||||
r = await client.patch("/api/admin/contact-messages/1", headers=admin_headers, json={"is_read": True})
|
||||
assert r.json()["is_read"] is True
|
||||
stats = (await client.get("/api/admin/dashboard/stats", headers=admin_headers)).json()
|
||||
assert stats["unread_contact_messages"] == 0
|
||||
assert (await client.delete("/api/admin/contact-messages/1", headers=admin_headers)).status_code == 204
|
||||
|
||||
|
||||
async def test_testimonials(client, editor_headers):
|
||||
r = await client.post(
|
||||
"/api/admin/testimonials",
|
||||
headers=editor_headers,
|
||||
json={"customer_name": "Mr. Das", "content": "Excellent installation!", "rating": 5},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
hidden = await client.post(
|
||||
"/api/admin/testimonials",
|
||||
headers=editor_headers,
|
||||
json={"customer_name": "Draft", "content": "Not yet public", "is_published": False},
|
||||
)
|
||||
assert hidden.status_code == 201
|
||||
bad = await client.post(
|
||||
"/api/admin/testimonials", headers=editor_headers, json={"customer_name": "X Y", "content": "Bad rating", "rating": 9}
|
||||
)
|
||||
assert bad.status_code == 422
|
||||
missing_project = await client.post(
|
||||
"/api/admin/testimonials", headers=editor_headers,
|
||||
json={"customer_name": "X Y", "content": "Linked", "project_id": 999},
|
||||
)
|
||||
assert missing_project.status_code == 422
|
||||
|
||||
public = (await client.get("/api/testimonials")).json()
|
||||
assert [t["customer_name"] for t in public] == ["Mr. Das"]
|
||||
assert "is_published" not in public[0]
|
||||
|
||||
r = await client.put("/api/admin/testimonials/2", headers=editor_headers, json={"is_published": True})
|
||||
assert r.status_code == 200
|
||||
assert len((await client.get("/api/testimonials")).json()) == 2
|
||||
assert (await client.delete("/api/admin/testimonials/2", headers=editor_headers)).status_code == 204
|
||||
|
||||
|
||||
async def test_site_content(client, editor_headers, admin_headers):
|
||||
r = await client.put(
|
||||
"/api/admin/content/hero",
|
||||
headers=editor_headers,
|
||||
json={"value": {"title": "Power your home with the sun", "cta": "Get a free quote"}},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert (await client.get("/api/content/hero")).json()["value"]["cta"] == "Get a free quote"
|
||||
assert (await client.get("/api/content")).json() == {
|
||||
"hero": {"title": "Power your home with the sun", "cta": "Get a free quote"}
|
||||
}
|
||||
assert (await client.put("/api/admin/content/Bad Key!", headers=editor_headers, json={"value": {}})).status_code == 422
|
||||
assert (await client.get("/api/content/missing")).status_code == 404
|
||||
assert (await client.delete("/api/admin/content/hero", headers=editor_headers)).status_code == 403
|
||||
assert (await client.delete("/api/admin/content/hero", headers=admin_headers)).status_code == 204
|
||||
@@ -0,0 +1,268 @@
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app.core.config import settings
|
||||
from tests.conftest import make_image
|
||||
|
||||
PROJECT = {
|
||||
"title": "5 kW Rooftop – Patia",
|
||||
"category": "residential",
|
||||
"location": "Patia, Bhubaneswar",
|
||||
"capacity_kw": 5,
|
||||
"installation_date": "2026-03-15",
|
||||
"description": "On-grid rooftop system.",
|
||||
}
|
||||
|
||||
|
||||
async def _project(client, headers, **overrides) -> dict:
|
||||
r = await client.post("/api/admin/projects", headers=headers, json={**PROJECT, **overrides})
|
||||
assert r.status_code == 201, r.text
|
||||
return r.json()
|
||||
|
||||
|
||||
def _files(*items):
|
||||
return [("files", (name, data, mime)) for name, data, mime in items]
|
||||
|
||||
|
||||
async def test_project_crud_and_publishing(client, editor_headers):
|
||||
p = await _project(client, editor_headers)
|
||||
assert p["slug"] == "5-kw-rooftop-patia"
|
||||
assert p["is_published"] is False
|
||||
p2 = await _project(client, editor_headers)
|
||||
assert p2["slug"] == "5-kw-rooftop-patia-2"
|
||||
|
||||
bad = await client.post("/api/admin/projects", headers=editor_headers, json={**PROJECT, "capacity_kw": -1, "category": "space"})
|
||||
assert bad.status_code == 422
|
||||
|
||||
# unpublished projects are hidden from the public site
|
||||
assert (await client.get("/api/projects")).json()["total"] == 0
|
||||
assert (await client.get(f"/api/projects/{p['id']}")).status_code == 404
|
||||
|
||||
r = await client.put(f"/api/admin/projects/{p['id']}", headers=editor_headers, json={"is_published": True, "capacity_kw": 6.5})
|
||||
assert r.status_code == 200 and r.json()["capacity_kw"] == 6.5
|
||||
assert (await client.put(f"/api/admin/projects/{p['id']}", headers=editor_headers, json={"title": None})).status_code == 422
|
||||
|
||||
public = (await client.get("/api/projects")).json()
|
||||
assert public["total"] == 1
|
||||
assert "is_published" not in public["items"][0]
|
||||
assert (await client.get(f"/api/projects/{p['slug']}")).status_code == 200
|
||||
assert (await client.get("/api/projects", params={"category": "commercial"})).json()["total"] == 0
|
||||
|
||||
lst = (await client.get("/api/admin/projects", params={"search": "patia"}, headers=editor_headers)).json()
|
||||
assert lst["total"] == 2
|
||||
|
||||
assert (await client.delete(f"/api/admin/projects/{p2['id']}", headers=editor_headers)).status_code == 204
|
||||
assert (await client.get(f"/api/admin/projects/{p2['id']}", headers=editor_headers)).status_code == 404
|
||||
|
||||
|
||||
async def test_upload_jpeg_png_webp_with_watermark_and_thumbnails(client, editor_headers, upload_dir):
|
||||
p = await _project(client, editor_headers, is_published=True)
|
||||
jpeg = make_image("JPEG", (2400, 1600), quality=95)
|
||||
png = make_image("PNG", (1200, 900), mode="RGBA")
|
||||
webp = make_image("WEBP", (800, 1200), quality=90)
|
||||
|
||||
r = await client.post(
|
||||
f"/api/admin/projects/{p['id']}/images",
|
||||
headers=editor_headers,
|
||||
files=_files(("roof.jpg", jpeg, "image/jpeg"), ("site.PNG", png, "image/png"), ("panel.webp", webp, "image/webp")),
|
||||
)
|
||||
assert r.status_code == 201, r.text
|
||||
body = r.json()
|
||||
uploaded = body["uploaded"]
|
||||
assert [u["mime_type"] for u in uploaded] == ["image/jpeg", "image/png", "image/webp"]
|
||||
assert [u["is_featured"] for u in uploaded] == [True, False, False]
|
||||
assert body["project"]["featured_image"]["id"] == uploaded[0]["id"]
|
||||
|
||||
for u, (w, h), src in zip(uploaded, [(2400, 1600), (1200, 900), (800, 1200)], [jpeg, png, webp], strict=True):
|
||||
assert (u["width"], u["height"]) == (w, h) # aspect ratio + size preserved
|
||||
assert u["file_size"] == len(src)
|
||||
name = u["url"].rsplit("/", 1)[-1]
|
||||
assert len(name.split(".")[0]) == 32 # server-generated uuid name
|
||||
|
||||
orig_path = next((upload_dir / "originals").glob(name.split(".")[0] + ".*"))
|
||||
assert orig_path.read_bytes() == src # original kept byte-for-byte
|
||||
|
||||
marked = Image.open(upload_dir / "watermarked" / name)
|
||||
original = Image.open(io.BytesIO(src)).convert("RGB")
|
||||
marked_rgb = marked.convert("RGB")
|
||||
assert marked.size == original.size
|
||||
# watermark: clearly visible change confined to the bottom-right corner
|
||||
from PIL import ImageChops
|
||||
|
||||
changed = ImageChops.difference(original, marked_rgb).convert("L").point(lambda v: 255 if v > 30 else 0)
|
||||
x0, y0, x1, y1 = changed.getbbox()
|
||||
assert x0 > w / 2 and y0 > h / 2, "watermark not in bottom-right"
|
||||
assert _region_diff(original, marked_rgb, (x0, y0, x1, y1)) > 25, "watermark too faint"
|
||||
diff_tl = _region_diff(original, marked_rgb, (0, 0, int(w * 0.5), int(h * 0.5)))
|
||||
assert diff_tl < 3, f"photo altered outside watermark ({diff_tl})"
|
||||
|
||||
thumb = Image.open(upload_dir / "thumbnails" / u["thumbnail_url"].rsplit("/", 1)[-1])
|
||||
assert thumb.format == "WEBP"
|
||||
assert max(thumb.size) == settings.THUMBNAIL_MAX_SIZE
|
||||
|
||||
# public gallery returns watermarked URLs, which are actually served
|
||||
detail = (await client.get(f"/api/projects/{p['slug']}")).json()
|
||||
assert len(detail["images"]) == 3
|
||||
assert "original_filename" not in detail["images"][0]
|
||||
path = detail["images"][0]["url"].replace("http://testserver", "")
|
||||
served = await client.get(path)
|
||||
assert served.status_code == 200 and served.headers["content-type"] == "image/jpeg"
|
||||
|
||||
# originals are never publicly reachable
|
||||
orig_name = next((upload_dir / "originals").glob("*")).name
|
||||
assert (await client.get(f"/media/originals/{orig_name}")).status_code == 404
|
||||
# ...but admins can download them
|
||||
dl = await client.get(uploaded[0]["original_download_path"], headers=editor_headers)
|
||||
assert dl.status_code == 200 and dl.content == jpeg
|
||||
assert (await client.get(uploaded[0]["original_download_path"])).status_code == 401
|
||||
|
||||
|
||||
def _region_diff(a: Image.Image, b: Image.Image, box) -> float:
|
||||
from PIL import ImageChops, ImageStat
|
||||
|
||||
return max(ImageStat.Stat(ImageChops.difference(a.crop(box), b.crop(box))).mean)
|
||||
|
||||
|
||||
async def test_invalid_uploads_rejected(client, editor_headers, upload_dir, monkeypatch):
|
||||
p = await _project(client, editor_headers)
|
||||
url = f"/api/admin/projects/{p['id']}/images"
|
||||
|
||||
cases = [
|
||||
(("notes.txt", b"hello", "text/plain"), 415),
|
||||
(("fake.jpg", b"this is not an image at all", "image/jpeg"), 400),
|
||||
(("evil.gif", make_image("GIF"), "image/gif"), 415),
|
||||
(("mismatch.jpg", make_image("PNG"), "image/jpeg"), 415), # content PNG, name .jpg
|
||||
(("empty.png", b"", "image/png"), 400),
|
||||
(("truncated.jpg", make_image("JPEG")[:2000], "image/jpeg"), 400),
|
||||
]
|
||||
for file, code in cases:
|
||||
r = await client.post(url, headers=editor_headers, files=_files(file))
|
||||
assert r.status_code == code, (file[0], r.status_code, r.text)
|
||||
assert r.json()["detail"]["errors"]
|
||||
|
||||
# one bad file in a batch -> whole batch rejected, nothing written
|
||||
r = await client.post(
|
||||
url,
|
||||
headers=editor_headers,
|
||||
files=_files(("ok.jpg", make_image("JPEG"), "image/jpeg"), ("bad.jpg", b"junk", "image/jpeg")),
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert not any(list((upload_dir / d).glob("*")) for d in ("originals", "watermarked", "thumbnails"))
|
||||
|
||||
# size limit
|
||||
monkeypatch.setattr(settings, "MAX_UPLOAD_SIZE_MB", 1)
|
||||
big = make_image("PNG", (3000, 3000), mode="RGB", compress_level=0)
|
||||
assert len(big) > 1024 * 1024
|
||||
r = await client.post(url, headers=editor_headers, files=_files(("big.png", big, "image/png")))
|
||||
assert r.status_code == 413
|
||||
|
||||
# no files at all
|
||||
r = await client.post(url, headers=editor_headers)
|
||||
assert r.status_code == 422
|
||||
|
||||
# unknown project
|
||||
r = await client.post("/api/admin/projects/999/images", headers=editor_headers,
|
||||
files=_files(("ok.jpg", make_image("JPEG"), "image/jpeg")))
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
async def test_path_traversal_filename_is_neutralised(client, editor_headers, upload_dir):
|
||||
p = await _project(client, editor_headers)
|
||||
r = await client.post(
|
||||
f"/api/admin/projects/{p['id']}/images",
|
||||
headers=editor_headers,
|
||||
files=_files(("../../../etc/evil.jpg", make_image("JPEG"), "image/jpeg")),
|
||||
)
|
||||
assert r.status_code == 201
|
||||
img = r.json()["uploaded"][0]
|
||||
assert img["original_filename"] == "evil.jpg"
|
||||
assert ".." not in img["url"]
|
||||
assert len(list((upload_dir / "originals").glob("*"))) == 1
|
||||
|
||||
|
||||
async def test_featured_image_and_deletion(client, editor_headers, upload_dir):
|
||||
p = await _project(client, editor_headers)
|
||||
r = await client.post(
|
||||
f"/api/admin/projects/{p['id']}/images",
|
||||
headers=editor_headers,
|
||||
files=_files(*[(f"p{i}.jpg", make_image("JPEG"), "image/jpeg") for i in range(3)]),
|
||||
)
|
||||
ids = [u["id"] for u in r.json()["uploaded"]]
|
||||
|
||||
r = await client.patch(f"/api/admin/project-images/{ids[2]}", headers=editor_headers,
|
||||
json={"is_featured": True, "caption": "Completed array"})
|
||||
assert r.status_code == 200
|
||||
featured = [i for i in r.json()["images"] if i["is_featured"]]
|
||||
assert [f["id"] for f in featured] == [ids[2]]
|
||||
assert r.json()["featured_image"]["caption"] == "Completed array"
|
||||
|
||||
# second upload batch keeps existing featured image and appends sort order
|
||||
r = await client.post(f"/api/admin/projects/{p['id']}/images", headers=editor_headers,
|
||||
files=_files(("more.webp", make_image("WEBP"), "image/webp")))
|
||||
assert r.json()["uploaded"][0]["is_featured"] is False
|
||||
assert r.json()["uploaded"][0]["sort_order"] == 3
|
||||
|
||||
# deleting the featured image removes its files and promotes another image
|
||||
assert len(list((upload_dir / "watermarked").glob("*"))) == 4
|
||||
assert (await client.delete(f"/api/admin/project-images/{ids[2]}", headers=editor_headers)).status_code == 204
|
||||
for d in ("originals", "watermarked", "thumbnails"):
|
||||
assert len(list((upload_dir / d).glob("*"))) == 3
|
||||
proj = (await client.get(f"/api/admin/projects/{p['id']}", headers=editor_headers)).json()
|
||||
assert proj["featured_image"]["id"] == ids[0]
|
||||
assert sum(i["is_featured"] for i in proj["images"]) == 1
|
||||
assert (await client.delete(f"/api/admin/project-images/{ids[2]}", headers=editor_headers)).status_code == 404
|
||||
|
||||
# deleting the project removes all of its files
|
||||
assert (await client.delete(f"/api/admin/projects/{p['id']}", headers=editor_headers)).status_code == 204
|
||||
for d in ("originals", "watermarked", "thumbnails"):
|
||||
assert list((upload_dir / d).glob("*")) == []
|
||||
|
||||
|
||||
async def test_upload_fails_cleanly_without_logo(client, editor_headers, monkeypatch, tmp_path, upload_dir):
|
||||
p = await _project(client, editor_headers)
|
||||
monkeypatch.setattr(settings, "WATERMARK_LOGO_PATH", tmp_path / "missing.png")
|
||||
r = await client.post(f"/api/admin/projects/{p['id']}/images", headers=editor_headers,
|
||||
files=_files(("a.jpg", make_image("JPEG"), "image/jpeg")))
|
||||
assert r.status_code == 503
|
||||
assert "logo" in r.json()["detail"].lower()
|
||||
assert list((upload_dir / "originals").glob("*")) == []
|
||||
|
||||
|
||||
async def test_services_with_watermarked_image(client, editor_headers, upload_dir):
|
||||
r = await client.post("/api/admin/services", headers=editor_headers,
|
||||
json={"title": "Rooftop Solar", "short_description": "Homes", "sort_order": 1})
|
||||
assert r.status_code == 201
|
||||
sid = r.json()["id"]
|
||||
assert r.json()["slug"] == "rooftop-solar"
|
||||
assert (await client.get("/api/services")).json() == []
|
||||
|
||||
r = await client.put(f"/api/admin/services/{sid}", headers=editor_headers,
|
||||
json={"is_published": True, "description": "Full description"})
|
||||
assert r.status_code == 200
|
||||
|
||||
r = await client.post(f"/api/admin/services/{sid}/image", headers=editor_headers,
|
||||
files={"file": ("svc.png", make_image("PNG"), "image/png")})
|
||||
assert r.status_code == 200, r.text
|
||||
first_url = r.json()["image_url"]
|
||||
assert first_url and r.json()["thumbnail_url"]
|
||||
|
||||
# replacing deletes the old files
|
||||
r = await client.post(f"/api/admin/services/{sid}/image", headers=editor_headers,
|
||||
files={"file": ("svc2.jpg", make_image("JPEG"), "image/jpeg")})
|
||||
assert r.json()["image_url"] != first_url
|
||||
assert len(list((upload_dir / "watermarked").glob("*"))) == 1
|
||||
|
||||
bad = await client.post(f"/api/admin/services/{sid}/image", headers=editor_headers,
|
||||
files={"file": ("x.jpg", b"nope", "image/jpeg")})
|
||||
assert bad.status_code == 400
|
||||
|
||||
public = (await client.get("/api/services")).json()
|
||||
assert len(public) == 1 and "is_published" not in public[0]
|
||||
assert (await client.get("/api/services/rooftop-solar")).status_code == 200
|
||||
|
||||
r = await client.delete(f"/api/admin/services/{sid}/image", headers=editor_headers)
|
||||
assert r.json()["image_url"] is None
|
||||
assert list((upload_dir / "watermarked").glob("*")) == []
|
||||
assert (await client.delete(f"/api/admin/services/{sid}", headers=editor_headers)).status_code == 204
|
||||
assert (await client.get("/api/services/rooftop-solar")).status_code == 404
|
||||
@@ -0,0 +1,107 @@
|
||||
from email import message_from_bytes
|
||||
|
||||
from app.core.config import settings
|
||||
from app.services.quotation import DEFAULT_QUOTE_SETTINGS, calculate_quote, format_inr
|
||||
from tests.conftest import make_image
|
||||
|
||||
|
||||
def test_format_inr_indian_grouping():
|
||||
assert format_inr(59500) == "₹59,500"
|
||||
assert format_inr(197000) == "₹1,97,000"
|
||||
assert format_inr(8420000) == "₹84,20,000"
|
||||
assert format_inr(999) == "₹999"
|
||||
|
||||
|
||||
def test_quote_matches_design_rates_and_subsidy_rules():
|
||||
cfg = dict(DEFAULT_QUOTE_SETTINGS)
|
||||
q = calculate_quote(cfg, "residential", 250, "Bhubaneswar, India")
|
||||
assert q.capacity_kw == 2.5
|
||||
assert q.panel_cost == 92_500 and q.installation_cost == 22_500 # as in Figma
|
||||
assert q.subsidy == 69_000 # 2 kW x 30,000 + 0.5 kW x 18,000
|
||||
assert q.total_after_subsidy == 92_500 + 22_500 - 69_000
|
||||
|
||||
big = calculate_quote(cfg, "residential", 2000, "")
|
||||
assert big.capacity_kw == 20 and big.subsidy == 78_000 # capped
|
||||
assert big.panel_cost == 740_000 and big.installation_cost == 180_000 # as in Figma
|
||||
|
||||
com = calculate_quote(cfg, "commercial", 500, "")
|
||||
assert com.subsidy == 0 and com.total_after_subsidy == 230_000
|
||||
|
||||
clamped = calculate_quote(cfg, "residential", 999_999, "")
|
||||
assert clamped.roof_area_sqft == cfg["max_area_sqft"]
|
||||
|
||||
|
||||
async def test_quote_endpoints_and_admin_overrides(client, admin_headers):
|
||||
r = await client.post("/api/quotations/calculate", json={"property_type": "residential", "roof_area_sqft": 500})
|
||||
assert r.status_code == 200 and r.json()["capacity_kw"] == 5
|
||||
|
||||
await client.put("/api/admin/content/quote_settings", headers=admin_headers,
|
||||
json={"value": {"panel_cost_per_kw": 40000, "sqft_per_kw": "abc"}})
|
||||
s = (await client.get("/api/quotations/settings")).json()
|
||||
assert s["panel_cost_per_kw"] == 40000 and s["sqft_per_kw"] == 100 # invalid value ignored
|
||||
r = await client.post("/api/quotations/calculate", json={"roof_area_sqft": 500})
|
||||
assert r.json()["panel_cost"] == 200_000
|
||||
|
||||
bad = await client.post("/api/quotations/calculate", json={"property_type": "villa", "roof_area_sqft": 0})
|
||||
assert bad.status_code == 422
|
||||
|
||||
|
||||
async def test_quote_pdf(client):
|
||||
r = await client.post("/api/quotations/pdf", json={"property_type": "commercial", "roof_area_sqft": 750, "location": "Cuttack"})
|
||||
assert r.status_code == 200
|
||||
assert r.headers["content-type"] == "application/pdf"
|
||||
assert r.content.startswith(b"%PDF")
|
||||
|
||||
|
||||
async def test_email_quote_saves_lead_and_writes_outbox(client, admin_headers, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(settings, "OUTBOX_DIR", tmp_path)
|
||||
r = await client.post("/api/quotations/email",
|
||||
json={"roof_area_sqft": 750, "location": "Puri", "email": "lead@example.com"})
|
||||
assert r.status_code == 200
|
||||
assert "sent to your email" in r.json()["message"]
|
||||
|
||||
files = list(tmp_path.glob("*.eml"))
|
||||
assert len(files) == 1
|
||||
msg = message_from_bytes(files[0].read_bytes())
|
||||
assert msg["To"] == "lead@example.com"
|
||||
assert any(p.get_filename() == "saura-shakti-quotation.pdf" for p in msg.walk())
|
||||
|
||||
enquiries = (await client.get("/api/admin/enquiries", headers=admin_headers)).json()
|
||||
assert enquiries["total"] == 1
|
||||
lead = enquiries["items"][0]
|
||||
assert lead["source"] == "quote_calculator" and lead["phone"] is None
|
||||
assert lead["required_capacity_kw"] == 7.5
|
||||
|
||||
# honeypot: nothing saved or sent
|
||||
await client.post("/api/quotations/email", json={"roof_area_sqft": 750, "email": "bot@example.com", "website": "x"})
|
||||
assert len(list(tmp_path.glob("*.eml"))) == 1
|
||||
bad = await client.post("/api/quotations/email", json={"roof_area_sqft": 750, "email": "nope"})
|
||||
assert bad.status_code == 422
|
||||
|
||||
|
||||
async def test_newsletter(client, admin_headers, editor_headers):
|
||||
assert (await client.post("/api/subscribe", json={"email": "Fan@Example.com"})).status_code == 201
|
||||
assert (await client.post("/api/subscribe", json={"email": "fan@example.com"})).status_code == 201 # idempotent
|
||||
assert (await client.post("/api/subscribe", json={"email": "bad"})).status_code == 422
|
||||
lst = (await client.get("/api/admin/subscribers", headers=editor_headers)).json()
|
||||
assert lst["total"] == 1 and lst["items"][0]["email"] == "fan@example.com"
|
||||
assert (await client.delete("/api/admin/subscribers/1", headers=editor_headers)).status_code == 403
|
||||
assert (await client.delete("/api/admin/subscribers/1", headers=admin_headers)).status_code == 204
|
||||
|
||||
|
||||
async def test_testimonial_video_and_image(client, editor_headers, upload_dir):
|
||||
bad = await client.post("/api/admin/testimonials", headers=editor_headers,
|
||||
json={"customer_name": "Rajesh Kumar", "video_url": "javascript:alert(1)"})
|
||||
assert bad.status_code == 422
|
||||
r = await client.post("/api/admin/testimonials", headers=editor_headers,
|
||||
json={"customer_name": "Rajesh Kumar", "designation": "Homeowner",
|
||||
"video_url": "https://www.youtube.com/watch?v=abc123"})
|
||||
assert r.status_code == 201 and r.json()["content"] is None
|
||||
tid = r.json()["id"]
|
||||
r = await client.post(f"/api/admin/testimonials/{tid}/image", headers=editor_headers,
|
||||
files={"file": ("still.jpg", make_image("JPEG"), "image/jpeg")})
|
||||
assert r.status_code == 200 and r.json()["thumbnail_url"]
|
||||
pub = (await client.get("/api/testimonials")).json()[0]
|
||||
assert pub["video_url"].startswith("https://") and pub["image_url"]
|
||||
assert (await client.delete(f"/api/admin/testimonials/{tid}", headers=editor_headers)).status_code == 204
|
||||
assert list((upload_dir / "watermarked").glob("*")) == []
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Unit tests for the watermark algorithm itself (no HTTP / DB)."""
|
||||
|
||||
from PIL import Image, ImageChops, ImageStat
|
||||
|
||||
from app.core.config import settings
|
||||
from app.services.image_processing import apply_watermark
|
||||
|
||||
|
||||
def _logo(path) -> Image.Image:
|
||||
return Image.open(path).convert("RGBA")
|
||||
|
||||
|
||||
def _bbox_of_change(a: Image.Image, b: Image.Image):
|
||||
return ImageChops.difference(a.convert("RGB"), b.convert("RGB")).getbbox()
|
||||
|
||||
|
||||
def test_watermark_bottom_right_and_proportional(logo_path):
|
||||
logo = _logo(logo_path)
|
||||
for size in [(4000, 3000), (1200, 800), (800, 1200), (300, 200)]:
|
||||
img = Image.new("RGB", size, (90, 120, 150))
|
||||
out = apply_watermark(img, logo)
|
||||
assert out.size == size
|
||||
x0, y0, x1, y1 = _bbox_of_change(img, out)
|
||||
W, H = size
|
||||
assert x0 > W / 2 and y0 > H / 2, "watermark must sit in the bottom-right quadrant"
|
||||
margin = max(8, round(min(W, H) * settings.WATERMARK_MARGIN_RATIO))
|
||||
assert W - x1 <= margin + 2 and H - y1 <= margin + 2 # consistent margins (halo may bleed slightly)
|
||||
# scales with image size, capped at 50% width for small images
|
||||
assert (x1 - x0) <= W * 0.5 + 10
|
||||
|
||||
|
||||
def test_logo_aspect_ratio_never_distorted(logo_path):
|
||||
logo = _logo(logo_path)
|
||||
img = Image.new("RGB", (2000, 2000), (0, 0, 0))
|
||||
out = apply_watermark(img, logo)
|
||||
# Find the solid logo area: pixels clearly brighter than the halo
|
||||
diff = ImageChops.difference(img, out.convert("RGB")).convert("L").point(lambda v: 255 if v > 100 else 0)
|
||||
x0, y0, x1, y1 = diff.getbbox()
|
||||
w, h = x1 - x0, y1 - y0
|
||||
# fixture content is 400x80 inside a 400x120 canvas -> ratio 5.0
|
||||
assert abs((w / h) - 5.0) < 0.25
|
||||
|
||||
|
||||
def test_visible_on_bright_and_dark_photos(logo_path):
|
||||
logo = _logo(logo_path) # white logo -> hardest case is a white photo
|
||||
for colour in [(255, 255, 255), (0, 0, 0), (128, 128, 128)]:
|
||||
img = Image.new("RGB", (1600, 1000), colour)
|
||||
out = apply_watermark(img, logo).convert("RGB")
|
||||
box = _bbox_of_change(img, out)
|
||||
region_diff = ImageStat.Stat(ImageChops.difference(img.crop(box), out.crop(box))).mean
|
||||
assert max(region_diff) > 20, f"watermark not visible on {colour}"
|
||||
|
||||
|
||||
def test_transparency_keeps_photo_visible(logo_path):
|
||||
logo = _logo(logo_path)
|
||||
img = Image.new("RGB", (1600, 1000), (20, 140, 60))
|
||||
out = apply_watermark(img, logo).convert("RGB")
|
||||
x0, y0, x1, y1 = _bbox_of_change(img, out)
|
||||
centre = out.getpixel(((x0 + x1) // 2, (y0 + y1) // 2))
|
||||
# with partial opacity the green photo still shows through the white logo
|
||||
assert centre != (255, 255, 255)
|
||||
assert centre[1] > centre[0]
|
||||
Reference in New Issue
Block a user