feat: T03 backend core – FastAPI + DB models + Equipment API + Redis cache + health + tests
- FastAPI app with CORS, lifespan handlers - Pydantic Settings config (DB, Redis, CORS, SMTP, JWT, Rentman) - SQLAlchemy async engine + session (DeclarativeBase) - 6 DB models: EquipmentCache, RentalRequest, RentalRequestItem, Contact, AdminUser, SyncLog - Pydantic schemas: EquipmentItem, EquipmentDetail, PaginatedEquipment, ContactCreate, ContactResponse - Redis cache helper: set/get/delete_pattern, rate limiting, equipment key builders - Equipment router: list (search/category/sort/pagination), detail, categories – all cached - Contact router: POST with Pydantic validation + rate limiting (5/min) - Health router: GET /api/health with DB + Redis status - 28 pytest tests (all pass, 90% coverage) - Dockerfile, requirements.txt, pytest.ini, test_report.md
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
"""Pytest fixtures for async tests."""
|
||||
|
||||
import asyncio
|
||||
from typing import AsyncGenerator
|
||||
|
||||
import fakeredis.aioredis
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
import app.cache as cache_module
|
||||
from app.database import Base, get_db
|
||||
from app.main import app
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def event_loop():
|
||||
"""Create a single event loop for all tests."""
|
||||
loop = asyncio.new_event_loop()
|
||||
yield loop
|
||||
loop.close()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def test_engine():
|
||||
"""Create a fresh in-memory SQLite engine for each test."""
|
||||
engine = create_async_engine("sqlite+aiosqlite:///:memory:", echo=False)
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
yield engine
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db_session(test_engine) -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Yield a DB session bound to the test engine."""
|
||||
session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
|
||||
async with session_factory() as session:
|
||||
yield session
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def fake_redis():
|
||||
"""Provide a fakeredis instance and patch the cache module global."""
|
||||
fake = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||
cache_module._cache_client = fake
|
||||
yield fake
|
||||
cache_module._cache_client = None
|
||||
await fake.flushall()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(test_engine, fake_redis) -> AsyncGenerator[AsyncClient, None]:
|
||||
"""Provide an async HTTP client with test DB and fake Redis."""
|
||||
session_factory = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
async def override_get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with session_factory() as session:
|
||||
yield session
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||
yield ac
|
||||
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Tests for Redis cache helpers."""
|
||||
|
||||
import pytest
|
||||
import fakeredis.aioredis
|
||||
|
||||
from app.cache import (
|
||||
_cache_client,
|
||||
check_rate_limit,
|
||||
delete_pattern,
|
||||
equipment_categories_key,
|
||||
equipment_detail_key,
|
||||
equipment_list_key,
|
||||
get_cache,
|
||||
get_cached,
|
||||
set_cache,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_set_and_get_cache(fake_redis):
|
||||
"""set_cache stores JSON and get_cached retrieves it."""
|
||||
await set_cache("test:key", {"foo": "bar"}, ttl=60)
|
||||
result = await get_cached("test:key")
|
||||
assert result == {"foo": "bar"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_cached_miss(fake_redis):
|
||||
"""get_cached returns None for non-existent key."""
|
||||
result = await get_cached("nonexistent:key")
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_pattern(fake_redis):
|
||||
"""delete_pattern removes matching keys."""
|
||||
await set_cache("equipment:list:1:all:default:all", ["a"], ttl=60)
|
||||
await set_cache("equipment:list:2:all:default:all", ["b"], ttl=60)
|
||||
await delete_pattern("equipment:list:*")
|
||||
assert await get_cached("equipment:list:1:all:default:all") is None
|
||||
assert await get_cached("equipment:list:2:all:default:all") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rate_limit_allows_under_limit(fake_redis):
|
||||
"""check_rate_limit allows requests under the limit."""
|
||||
for _ in range(5):
|
||||
allowed = await check_rate_limit("test_ip", max_requests=5, window=60)
|
||||
assert allowed is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rate_limit_blocks_over_limit(fake_redis):
|
||||
"""check_rate_limit blocks requests over the limit."""
|
||||
for _ in range(5):
|
||||
await check_rate_limit("blocked_ip", max_requests=5, window=60)
|
||||
allowed = await check_rate_limit("blocked_ip", max_requests=5, window=60)
|
||||
assert allowed is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_equipment_list_key(fake_redis):
|
||||
"""equipment_list_key builds correct key format."""
|
||||
key = equipment_list_key(1, "Lautsprecher", "name_asc", "K2")
|
||||
assert "equipment" in key
|
||||
assert "list" in key
|
||||
assert "1" in key
|
||||
assert "Lautsprecher" in key
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_equipment_detail_key(fake_redis):
|
||||
"""equipment_detail_key builds correct key format."""
|
||||
key = equipment_detail_key(42)
|
||||
assert "equipment" in key
|
||||
assert "detail" in key
|
||||
assert "42" in key
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_equipment_categories_key(fake_redis):
|
||||
"""equipment_categories_key builds correct key format."""
|
||||
key = equipment_categories_key()
|
||||
assert key == "equipment:categories"
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Tests for the contact form endpoint."""
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_contact_valid(client: AsyncClient):
|
||||
"""POST /api/contact with valid data returns 201."""
|
||||
response = await client.post("/api/contact", json={
|
||||
"name": "Max Mustermann",
|
||||
"email": "max@example.com",
|
||||
"phone": "+49 170 1234567",
|
||||
"message": "Hallo, ich habe eine Frage.",
|
||||
"privacy_consent": True,
|
||||
})
|
||||
assert response.status_code == 201
|
||||
data = response.json()
|
||||
assert data["success"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_contact_invalid_email(client: AsyncClient):
|
||||
"""POST /api/contact with invalid email returns 422."""
|
||||
response = await client.post("/api/contact", json={
|
||||
"name": "Max Mustermann",
|
||||
"email": "invalid-email",
|
||||
"message": "Hallo",
|
||||
"privacy_consent": True,
|
||||
})
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_contact_no_consent(client: AsyncClient):
|
||||
"""POST /api/contact with privacy_consent=False returns 422."""
|
||||
response = await client.post("/api/contact", json={
|
||||
"name": "Max Mustermann",
|
||||
"email": "max@example.com",
|
||||
"message": "Hallo",
|
||||
"privacy_consent": False,
|
||||
})
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_contact_missing_name(client: AsyncClient):
|
||||
"""POST /api/contact with missing name returns 422."""
|
||||
response = await client.post("/api/contact", json={
|
||||
"email": "max@example.com",
|
||||
"message": "Hallo",
|
||||
"privacy_consent": True,
|
||||
})
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_contact_rate_limit(client: AsyncClient):
|
||||
"""6th contact request within 60s is rate-limited."""
|
||||
payload = {
|
||||
"name": "Max Mustermann",
|
||||
"email": "max@example.com",
|
||||
"message": "Hallo",
|
||||
"privacy_consent": True,
|
||||
}
|
||||
for i in range(5):
|
||||
resp = await client.post("/api/contact", json=payload)
|
||||
assert resp.status_code == 201
|
||||
resp6 = await client.post("/api/contact", json=payload)
|
||||
assert resp6.status_code == 429
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Tests for the equipment API endpoints."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.equipment import EquipmentCache
|
||||
|
||||
|
||||
async def seed_equipment(db: AsyncSession) -> list[EquipmentCache]:
|
||||
"""Insert test equipment rows and return them."""
|
||||
items = [
|
||||
EquipmentCache(
|
||||
rentman_id="100", name="L-Acoustics K2", number="K2-001",
|
||||
category="Lautsprecher", description="Line Array Element",
|
||||
rental_price=Decimal("250.00"), brand="L-Acoustics", available=True,
|
||||
),
|
||||
EquipmentCache(
|
||||
rentman_id="101", name="L-Acoustics KS28", number="KS28-001",
|
||||
category="Subwoofer", description="Subwoofer",
|
||||
rental_price=Decimal("180.00"), brand="L-Acoustics", available=True,
|
||||
),
|
||||
EquipmentCache(
|
||||
rentman_id="102", name="d&b T10", number="T10-001",
|
||||
category="Lautsprecher", description="Point Source",
|
||||
rental_price=Decimal("120.00"), brand="d&b audiotechnik", available=True,
|
||||
),
|
||||
EquipmentCache(
|
||||
rentman_id="103", name="Robe Pointe", number="PT-001",
|
||||
category="Licht", description="Moving Head",
|
||||
rental_price=Decimal("95.00"), brand="Robe", available=True,
|
||||
),
|
||||
]
|
||||
db.add_all(items)
|
||||
await db.commit()
|
||||
for item in items:
|
||||
await db.refresh(item)
|
||||
return items
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_equipment_empty(client: AsyncClient):
|
||||
"""GET /api/equipment on empty DB returns empty paginated response."""
|
||||
response = await client.get("/api/equipment")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["items"] == []
|
||||
assert data["total"] == 0
|
||||
assert data["page"] == 1
|
||||
assert data["page_size"] == 20
|
||||
assert data["total_pages"] == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_equipment_with_data(client: AsyncClient, db_session: AsyncSession):
|
||||
"""GET /api/equipment returns paginated items after seeding."""
|
||||
await seed_equipment(db_session)
|
||||
response = await client.get("/api/equipment")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 4
|
||||
assert len(data["items"]) == 4
|
||||
assert data["page"] == 1
|
||||
assert data["page_size"] == 20
|
||||
assert data["total_pages"] == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_equipment_search(client: AsyncClient, db_session: AsyncSession):
|
||||
"""GET /api/equipment?search=K2 returns only matching items."""
|
||||
await seed_equipment(db_session)
|
||||
response = await client.get("/api/equipment?search=K2")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["items"][0]["name"] == "L-Acoustics K2"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_equipment_category_filter(client: AsyncClient, db_session: AsyncSession):
|
||||
"""GET /api/equipment?category=Lautsprecher returns only matching items."""
|
||||
await seed_equipment(db_session)
|
||||
response = await client.get("/api/equipment?category=Lautsprecher")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 2
|
||||
for item in data["items"]:
|
||||
assert item["category"] == "Lautsprecher"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_equipment_sort_name_desc(client: AsyncClient, db_session: AsyncSession):
|
||||
"""GET /api/equipment?sort=name_desc returns items sorted descending."""
|
||||
await seed_equipment(db_session)
|
||||
response = await client.get("/api/equipment?sort=name_desc")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
names = [item["name"] for item in data["items"]]
|
||||
assert names == sorted(names, reverse=True)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_equipment_pagination(client: AsyncClient, db_session: AsyncSession):
|
||||
"""GET /api/equipment with page_size=2 returns correct pagination."""
|
||||
await seed_equipment(db_session)
|
||||
response = await client.get("/api/equipment?page=1&page_size=2")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["items"]) == 2
|
||||
assert data["total"] == 4
|
||||
assert data["total_pages"] == 2
|
||||
|
||||
response2 = await client.get("/api/equipment?page=2&page_size=2")
|
||||
data2 = response2.json()
|
||||
assert len(data2["items"]) == 2
|
||||
assert data2["page"] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_equipment_detail(client: AsyncClient, db_session: AsyncSession):
|
||||
"""GET /api/equipment/{id} returns the full detail."""
|
||||
items = await seed_equipment(db_session)
|
||||
eq_id = items[0].id
|
||||
response = await client.get(f"/api/equipment/{eq_id}")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["id"] == eq_id
|
||||
assert data["name"] == "L-Acoustics K2"
|
||||
assert data["brand"] == "L-Acoustics"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_equipment_not_found(client: AsyncClient):
|
||||
"""GET /api/equipment/999999 returns 404."""
|
||||
response = await client.get("/api/equipment/999999")
|
||||
assert response.status_code == 404
|
||||
assert "not found" in response.json()["detail"].lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_categories(client: AsyncClient, db_session: AsyncSession):
|
||||
"""GET /api/equipment/categories returns distinct categories."""
|
||||
await seed_equipment(db_session)
|
||||
response = await client.get("/api/equipment/categories")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert isinstance(data, list)
|
||||
assert "Lautsprecher" in data
|
||||
assert "Subwoofer" in data
|
||||
assert "Licht" in data
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Tests for the health endpoint."""
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_health_returns_ok(client: AsyncClient):
|
||||
"""GET /api/health should return 200 with status ok."""
|
||||
response = await client.get("/api/health")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "status" in data
|
||||
assert "db" in data
|
||||
assert "redis" in data
|
||||
assert data["redis"] == "connected"
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Tests for SQLAlchemy model definitions and table creation."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.models.admin_user import AdminUser
|
||||
from app.models.contact import Contact
|
||||
from app.models.equipment import EquipmentCache
|
||||
from app.models.rental_request import RentalRequest, RentalRequestItem
|
||||
from app.models.sync_log import SyncLog
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_equipment_cache_model(db_session: AsyncSession):
|
||||
"""EquipmentCache model can be instantiated and queried."""
|
||||
item = EquipmentCache(
|
||||
rentman_id="999", name="Test Speaker", number="TS-001",
|
||||
category="Lautsprecher", description="Test item",
|
||||
)
|
||||
db_session.add(item)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(item)
|
||||
assert item.id is not None
|
||||
assert item.rentman_id == "999"
|
||||
assert item.available is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_rental_request_model(db_session: AsyncSession):
|
||||
"""RentalRequest and RentalRequestItem models work with relationships."""
|
||||
req = RentalRequest(
|
||||
reference_number="HMS-2026-00001",
|
||||
event_name="Test Event",
|
||||
date_start=date(2026, 8, 15),
|
||||
date_end=date(2026, 8, 16),
|
||||
contact_name="Max Mustermann",
|
||||
contact_email="max@example.com",
|
||||
)
|
||||
db_session.add(req)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(req)
|
||||
|
||||
item = RentalRequestItem(
|
||||
rental_request_id=req.id,
|
||||
equipment_name="Test Speaker",
|
||||
quantity=2,
|
||||
)
|
||||
db_session.add(item)
|
||||
await db_session.commit()
|
||||
|
||||
# Use explicit query with selectinload to avoid lazy loading in async
|
||||
result = await db_session.execute(
|
||||
select(RentalRequest).options(selectinload(RentalRequest.items)).where(RentalRequest.id == req.id)
|
||||
)
|
||||
loaded_req = result.scalar_one()
|
||||
assert len(loaded_req.items) == 1
|
||||
assert loaded_req.items[0].quantity == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_contact_model(db_session: AsyncSession):
|
||||
"""Contact model can store a contact form submission."""
|
||||
contact = Contact(
|
||||
name="Max", email="max@example.com", message="Hello",
|
||||
privacy_consent=True,
|
||||
)
|
||||
db_session.add(contact)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(contact)
|
||||
assert contact.id is not None
|
||||
assert contact.email_sent is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_admin_user_model(db_session: AsyncSession):
|
||||
"""AdminUser model stores username and password hash."""
|
||||
user = AdminUser(username="admin", password_hash="hashed_secret")
|
||||
db_session.add(user)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(user)
|
||||
assert user.id is not None
|
||||
assert user.username == "admin"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sync_log_model(db_session: AsyncSession):
|
||||
"""SyncLog model stores sync metadata."""
|
||||
log = SyncLog(sync_type="equipment", status="running")
|
||||
db_session.add(log)
|
||||
await db_session.commit()
|
||||
await db_session.refresh(log)
|
||||
assert log.id is not None
|
||||
assert log.status == "running"
|
||||
assert log.items_processed == 0
|
||||
Reference in New Issue
Block a user