eksplicit mapping af envs
This commit is contained in:
4
backend/.env.example
Normal file
4
backend/.env.example
Normal file
@@ -0,0 +1,4 @@
|
||||
REDIS_URL=redis://localhost:6379
|
||||
DATABASE_URL=postgresql+asyncpg://sighej:sighej@localhost/sighej
|
||||
SESSION_TTL_SECONDS=7200
|
||||
ALLOWED_ORIGINS=http://localhost:3000
|
||||
11
backend/Dockerfile
Normal file
11
backend/Dockerfile
Normal file
@@ -0,0 +1,11 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8000
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
15
backend/README.md
Normal file
15
backend/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# backend
|
||||
|
||||
FastAPI backend for Social Proximity.
|
||||
|
||||
See [Docs/BACKEND.md](../Docs/BACKEND.md) for full documentation.
|
||||
|
||||
## Quick start
|
||||
|
||||
```bash
|
||||
python -m venv .venv && source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
uvicorn app.main:app --reload --port 8000
|
||||
```
|
||||
|
||||
Or from root: `docker-compose up`
|
||||
0
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
9
backend/app/api/health.py
Normal file
9
backend/app/api/health.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health() -> JSONResponse:
|
||||
return JSONResponse({"status": "ok"})
|
||||
19
backend/app/api/match.py
Normal file
19
backend/app/api/match.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.match import MatchRequest, MatchResult
|
||||
from app.services import match_service, stats_service
|
||||
|
||||
router = APIRouter(tags=["match"])
|
||||
|
||||
|
||||
@router.post("", response_model=MatchResult)
|
||||
async def attempt_match(
|
||||
body: MatchRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> MatchResult:
|
||||
result = await match_service.attempt_match(body.own_token, body.detected_token)
|
||||
if result["match"]:
|
||||
await stats_service.increment_matches(db)
|
||||
return MatchResult(**result)
|
||||
18
backend/app/api/session.py
Normal file
18
backend/app/api/session.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.session import SessionCreate, SessionResponse
|
||||
from app.services import session_service, stats_service
|
||||
|
||||
router = APIRouter(tags=["session"])
|
||||
|
||||
|
||||
@router.post("", response_model=SessionResponse)
|
||||
async def create_session(
|
||||
body: SessionCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> SessionResponse:
|
||||
result = await session_service.create_session(body.ble_token, body.interests)
|
||||
await stats_service.increment_sessions(db)
|
||||
return SessionResponse(**result)
|
||||
14
backend/app/api/stats.py
Normal file
14
backend/app/api/stats.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.stats import StatsResponse
|
||||
from app.services import stats_service
|
||||
|
||||
router = APIRouter(tags=["stats"])
|
||||
|
||||
|
||||
@router.get("", response_model=StatsResponse)
|
||||
async def get_stats(db: AsyncSession = Depends(get_db)) -> StatsResponse:
|
||||
data = await stats_service.get_stats(db)
|
||||
return StatsResponse(**data)
|
||||
16
backend/app/api/ws.py
Normal file
16
backend/app/api/ws.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
|
||||
from app.services.ws_manager import manager
|
||||
|
||||
router = APIRouter(tags=["websocket"])
|
||||
|
||||
|
||||
@router.websocket("/ws/{ble_token}")
|
||||
async def websocket_endpoint(websocket: WebSocket, ble_token: str) -> None:
|
||||
await manager.connect(ble_token, websocket)
|
||||
try:
|
||||
while True:
|
||||
# Keep the connection alive; nudges are pushed server-side.
|
||||
await websocket.receive_text()
|
||||
except WebSocketDisconnect:
|
||||
manager.disconnect(ble_token)
|
||||
3
backend/app/core/__init__.py
Normal file
3
backend/app/core/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from app.core.config import settings # noqa: F401
|
||||
from app.core.database import get_db # noqa: F401
|
||||
from app.core.redis import get_client # noqa: F401
|
||||
13
backend/app/core/config.py
Normal file
13
backend/app/core/config.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
redis_url: str = "redis://localhost:6379"
|
||||
database_url: str = "postgresql+asyncpg://sighej:sighej@localhost/sighej"
|
||||
session_ttl_seconds: int = 7200
|
||||
allowed_origins: list[str] = ["http://localhost:3000"]
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
|
||||
|
||||
|
||||
settings = Settings()
|
||||
21
backend/app/core/database.py
Normal file
21
backend/app/core/database.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_async_engine(settings.database_url, echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
async def create_tables() -> None:
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
|
||||
async def get_db() -> AsyncSession:
|
||||
async with AsyncSessionLocal() as session:
|
||||
yield session
|
||||
16
backend/app/core/redis.py
Normal file
16
backend/app/core/redis.py
Normal file
@@ -0,0 +1,16 @@
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_pool: redis.ConnectionPool | None = None
|
||||
|
||||
|
||||
def get_pool() -> redis.ConnectionPool:
|
||||
global _pool
|
||||
if _pool is None:
|
||||
_pool = redis.ConnectionPool.from_url(settings.redis_url, decode_responses=True)
|
||||
return _pool
|
||||
|
||||
|
||||
def get_client() -> redis.Redis:
|
||||
return redis.Redis(connection_pool=get_pool())
|
||||
34
backend/app/main.py
Normal file
34
backend/app/main.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api import health, session, match, ws, stats
|
||||
from app.core.config import settings
|
||||
from app.core.database import create_tables
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await create_tables()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Social Proximity API",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.allowed_origins,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(session.router, prefix="/session")
|
||||
app.include_router(match.router, prefix="/match")
|
||||
app.include_router(ws.router)
|
||||
app.include_router(stats.router, prefix="/stats")
|
||||
0
backend/app/models/__init__.py
Normal file
0
backend/app/models/__init__.py
Normal file
20
backend/app/models/db_models.py
Normal file
20
backend/app/models/db_models.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class DailyStat(Base):
|
||||
__tablename__ = "daily_stats"
|
||||
|
||||
date: Mapped[sa.Date] = mapped_column(sa.Date, primary_key=True)
|
||||
total_sessions: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
total_matches: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
|
||||
|
||||
class InterestCategoryCount(Base):
|
||||
__tablename__ = "interest_category_counts"
|
||||
|
||||
date: Mapped[sa.Date] = mapped_column(sa.Date, primary_key=True)
|
||||
category: Mapped[str] = mapped_column(sa.String(64), primary_key=True)
|
||||
count: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
12
backend/app/models/match.py
Normal file
12
backend/app/models/match.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class MatchRequest(BaseModel):
|
||||
own_token: str
|
||||
detected_token: str
|
||||
|
||||
|
||||
class MatchResult(BaseModel):
|
||||
match: bool
|
||||
shared_interests: list[str]
|
||||
nudge_sent: bool
|
||||
13
backend/app/models/session.py
Normal file
13
backend/app/models/session.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class SessionCreate(BaseModel):
|
||||
ble_token: str = Field(..., min_length=1, max_length=128)
|
||||
interests: list[str] = Field(..., min_length=1, max_length=20)
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
session_id: str
|
||||
expires_at: datetime
|
||||
8
backend/app/models/stats.py
Normal file
8
backend/app/models/stats.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class StatsResponse(BaseModel):
|
||||
total_sessions_today: int
|
||||
total_matches_today: int
|
||||
active_sessions_now: int
|
||||
top_interest_categories: list[str]
|
||||
0
backend/app/services/__init__.py
Normal file
0
backend/app/services/__init__.py
Normal file
38
backend/app/services/match_service.py
Normal file
38
backend/app/services/match_service.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from app.services.session_service import get_session
|
||||
from app.services.ws_manager import manager
|
||||
|
||||
|
||||
async def attempt_match(own_token: str, detected_token: str) -> dict:
|
||||
"""
|
||||
Check if two nearby users share interests and both consent.
|
||||
Sends a WebSocket nudge to both if matched.
|
||||
"""
|
||||
own_session = await get_session(own_token)
|
||||
other_session = await get_session(detected_token)
|
||||
|
||||
if own_session is None or other_session is None:
|
||||
return {"match": False, "shared_interests": [], "nudge_sent": False}
|
||||
|
||||
own_interests = set(own_session.get("interests", []))
|
||||
other_interests = set(other_session.get("interests", []))
|
||||
shared = list(own_interests & other_interests)
|
||||
|
||||
if not shared:
|
||||
return {"match": False, "shared_interests": [], "nudge_sent": False}
|
||||
|
||||
nudge = {
|
||||
"type": "nudge",
|
||||
"shared_interests": shared,
|
||||
"message": f"Someone nearby shares your interest in {_format_interests(shared)}.",
|
||||
}
|
||||
|
||||
await manager.send(own_token, nudge)
|
||||
await manager.send(detected_token, nudge)
|
||||
|
||||
return {"match": True, "shared_interests": shared, "nudge_sent": True}
|
||||
|
||||
|
||||
def _format_interests(interests: list[str]) -> str:
|
||||
if len(interests) == 1:
|
||||
return interests[0]
|
||||
return ", ".join(interests[:-1]) + " and " + interests[-1]
|
||||
39
backend/app/services/session_service.py
Normal file
39
backend/app/services/session_service.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import json
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.redis import get_client
|
||||
|
||||
|
||||
async def create_session(ble_token: str, interests: list[str]) -> dict:
|
||||
"""Store an ephemeral BLE session in Redis with TTL."""
|
||||
client = get_client()
|
||||
session_id = str(uuid.uuid4())
|
||||
expires_at = datetime.now(UTC) + timedelta(seconds=settings.session_ttl_seconds)
|
||||
|
||||
payload = json.dumps({
|
||||
"session_id": session_id,
|
||||
"interests": interests,
|
||||
"created_at": datetime.now(UTC).isoformat(),
|
||||
})
|
||||
|
||||
await client.setex(f"session:{ble_token}", settings.session_ttl_seconds, payload)
|
||||
|
||||
return {"session_id": session_id, "expires_at": expires_at}
|
||||
|
||||
|
||||
async def get_session(ble_token: str) -> dict | None:
|
||||
"""Retrieve a session by BLE token. Returns None if expired or not found."""
|
||||
client = get_client()
|
||||
raw = await client.get(f"session:{ble_token}")
|
||||
if raw is None:
|
||||
return None
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
async def count_active_sessions() -> int:
|
||||
"""Return number of active (non-expired) sessions."""
|
||||
client = get_client()
|
||||
keys = await client.keys("session:*")
|
||||
return len(keys)
|
||||
60
backend/app/services/stats_service.py
Normal file
60
backend/app/services/stats_service.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.db_models import DailyStat, InterestCategoryCount
|
||||
from app.services.session_service import count_active_sessions
|
||||
|
||||
|
||||
async def get_stats(db: AsyncSession) -> dict:
|
||||
"""Return anonymised aggregate stats for the admin dashboard."""
|
||||
today = date.today()
|
||||
|
||||
row = await db.scalar(
|
||||
sa.select(DailyStat).where(DailyStat.date == today)
|
||||
)
|
||||
|
||||
top_categories_rows = await db.scalars(
|
||||
sa.select(InterestCategoryCount)
|
||||
.where(InterestCategoryCount.date == today)
|
||||
.order_by(InterestCategoryCount.count.desc())
|
||||
.limit(5)
|
||||
)
|
||||
top_categories = [r.category for r in top_categories_rows]
|
||||
active = await count_active_sessions()
|
||||
|
||||
return {
|
||||
"total_sessions_today": row.total_sessions if row else 0,
|
||||
"total_matches_today": row.total_matches if row else 0,
|
||||
"active_sessions_now": active,
|
||||
"top_interest_categories": top_categories,
|
||||
}
|
||||
|
||||
|
||||
async def increment_sessions(db: AsyncSession) -> None:
|
||||
"""Increment daily session counter. Called when a new session is created."""
|
||||
today = date.today()
|
||||
await db.execute(
|
||||
sa.dialects.postgresql.insert(DailyStat)
|
||||
.values(date=today, total_sessions=1, total_matches=0)
|
||||
.on_conflict_do_update(
|
||||
index_elements=["date"],
|
||||
set_={"total_sessions": DailyStat.total_sessions + 1},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def increment_matches(db: AsyncSession) -> None:
|
||||
"""Increment daily match counter. Called on a successful match."""
|
||||
today = date.today()
|
||||
await db.execute(
|
||||
sa.dialects.postgresql.insert(DailyStat)
|
||||
.values(date=today, total_sessions=0, total_matches=1)
|
||||
.on_conflict_do_update(
|
||||
index_elements=["date"],
|
||||
set_={"total_matches": DailyStat.total_matches + 1},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
25
backend/app/services/ws_manager.py
Normal file
25
backend/app/services/ws_manager.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import json
|
||||
|
||||
from fastapi import WebSocket
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Manages active WebSocket connections keyed by BLE token."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._connections: dict[str, WebSocket] = {}
|
||||
|
||||
async def connect(self, token: str, websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
self._connections[token] = websocket
|
||||
|
||||
def disconnect(self, token: str) -> None:
|
||||
self._connections.pop(token, None)
|
||||
|
||||
async def send(self, token: str, message: dict) -> None:
|
||||
websocket = self._connections.get(token)
|
||||
if websocket is not None:
|
||||
await websocket.send_text(json.dumps(message))
|
||||
|
||||
|
||||
manager = ConnectionManager()
|
||||
11
backend/pyproject.toml
Normal file
11
backend/pyproject.toml
Normal file
@@ -0,0 +1,11 @@
|
||||
[tool.pytest.ini_options]
|
||||
asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["."]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I"]
|
||||
ignore = ["E501"]
|
||||
4
backend/requirements-dev.txt
Normal file
4
backend/requirements-dev.txt
Normal file
@@ -0,0 +1,4 @@
|
||||
-r requirements.txt
|
||||
pytest>=8.0.0
|
||||
pytest-asyncio>=0.23.0
|
||||
httpx>=0.27.0
|
||||
8
backend/requirements.txt
Normal file
8
backend/requirements.txt
Normal file
@@ -0,0 +1,8 @@
|
||||
fastapi>=0.111.0
|
||||
uvicorn[standard]>=0.29.0
|
||||
pydantic>=2.7.0
|
||||
pydantic-settings>=2.2.0
|
||||
redis[asyncio]>=5.0.0
|
||||
asyncpg>=0.29.0
|
||||
sqlalchemy[asyncio]>=2.0.0
|
||||
websockets>=12.0
|
||||
12
backend/tests/test_health.py
Normal file
12
backend/tests/test_health.py
Normal file
@@ -0,0 +1,12 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_health() -> None:
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
response = await client.get("/health")
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {"status": "ok"}
|
||||
61
backend/tests/test_match.py
Normal file
61
backend/tests/test_match.py
Normal file
@@ -0,0 +1,61 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.match_service import attempt_match, _format_interests
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_match_when_sessions_missing() -> None:
|
||||
with patch("app.services.match_service.get_session", return_value=None):
|
||||
result = await attempt_match("token_a", "token_b")
|
||||
assert result["match"] is False
|
||||
assert result["nudge_sent"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_match_when_no_shared_interests() -> None:
|
||||
sessions = {
|
||||
"token_a": {"interests": ["devops"]},
|
||||
"token_b": {"interests": ["cooking"]},
|
||||
}
|
||||
|
||||
async def fake_get(token: str) -> dict:
|
||||
return sessions.get(token)
|
||||
|
||||
with patch("app.services.match_service.get_session", side_effect=fake_get):
|
||||
with patch("app.services.match_service.manager") as mock_mgr:
|
||||
result = await attempt_match("token_a", "token_b")
|
||||
|
||||
assert result["match"] is False
|
||||
mock_mgr.send.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_with_shared_interests() -> None:
|
||||
sessions = {
|
||||
"token_a": {"interests": ["devops", "hardstyle"]},
|
||||
"token_b": {"interests": ["hardstyle", "philosophy"]},
|
||||
}
|
||||
|
||||
async def fake_get(token: str) -> dict:
|
||||
return sessions.get(token)
|
||||
|
||||
with patch("app.services.match_service.get_session", side_effect=fake_get):
|
||||
with patch("app.services.match_service.manager") as mock_mgr:
|
||||
mock_mgr.send = AsyncMock()
|
||||
result = await attempt_match("token_a", "token_b")
|
||||
|
||||
assert result["match"] is True
|
||||
assert "hardstyle" in result["shared_interests"]
|
||||
assert result["nudge_sent"] is True
|
||||
assert mock_mgr.send.call_count == 2
|
||||
|
||||
|
||||
def test_format_interests_single() -> None:
|
||||
assert _format_interests(["devops"]) == "devops"
|
||||
|
||||
|
||||
def test_format_interests_multiple() -> None:
|
||||
result = _format_interests(["devops", "hardstyle"])
|
||||
assert result == "devops and hardstyle"
|
||||
68
backend/tests/test_stats.py
Normal file
68
backend/tests/test_stats.py
Normal file
@@ -0,0 +1,68 @@
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stats_zero_sessions() -> None:
|
||||
"""Stats endpoint returns zeroed StatsResponse when no data exists."""
|
||||
mock_db = AsyncMock()
|
||||
|
||||
with (
|
||||
patch("app.services.stats_service.count_active_sessions", return_value=0),
|
||||
patch("app.core.database.get_db", return_value=mock_db),
|
||||
):
|
||||
# DB returns None for DailyStat row and empty for interest categories
|
||||
mock_db.scalar = AsyncMock(return_value=None)
|
||||
mock_db.scalars = AsyncMock(return_value=iter([]))
|
||||
|
||||
async with AsyncClient(
|
||||
transport=ASGITransport(app=app), base_url="http://test"
|
||||
) as client:
|
||||
response = await client.get("/stats")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "active_sessions_now" in data
|
||||
assert "total_sessions_today" in data
|
||||
assert "total_matches_today" in data
|
||||
assert "top_interest_categories" in data
|
||||
assert data["active_sessions_now"] == 0
|
||||
assert data["total_sessions_today"] == 0
|
||||
assert data["total_matches_today"] == 0
|
||||
assert data["top_interest_categories"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stats_with_data() -> None:
|
||||
"""Stats endpoint returns correct values when DailyStat row exists."""
|
||||
mock_stat = MagicMock()
|
||||
mock_stat.total_sessions = 12
|
||||
mock_stat.total_matches = 5
|
||||
|
||||
mock_category = MagicMock()
|
||||
mock_category.category = "hiking"
|
||||
|
||||
mock_db = AsyncMock()
|
||||
|
||||
with (
|
||||
patch("app.services.stats_service.count_active_sessions", return_value=3),
|
||||
patch("app.core.database.get_db", return_value=mock_db),
|
||||
):
|
||||
mock_db.scalar = AsyncMock(return_value=mock_stat)
|
||||
mock_db.scalars = AsyncMock(return_value=iter([mock_category]))
|
||||
|
||||
async with AsyncClient(
|
||||
transport=ASGITransport(app=app), base_url="http://test"
|
||||
) as client:
|
||||
response = await client.get("/stats")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["active_sessions_now"] == 3
|
||||
assert data["total_sessions_today"] == 12
|
||||
assert data["total_matches_today"] == 5
|
||||
assert data["top_interest_categories"] == ["hiking"]
|
||||
Reference in New Issue
Block a user