Files
skipredictor/tests/test_auth.py
T
dasemu 9d97afe538 feat(api): add FastAPI backend with JWT authentication
REST API serving forecast data with HS256 JWT auth (14-day tokens).
Public: /health, /auth/register, /auth/login.
Protected: /stations, /forecast, /forecast/history, /forecast/{id}, /status.
Includes APScheduler for periodic forecasts and Telegram bot subprocess.
2026-03-13 09:36:18 +01:00

114 lines
3.1 KiB
Python

"""Integration tests for JWT authentication."""
from __future__ import annotations
import os
import pytest
from fastapi.testclient import TestClient
# Ensure JWT_SECRET_KEY is set before importing the app
os.environ.setdefault("JWT_SECRET_KEY", "test-secret-key-for-testing-only")
from app.main import app # noqa: E402
client = TestClient(app, raise_server_exceptions=False)
_TEST_EMAIL = "test@example.com"
_TEST_PASSWORD = "securepassword123"
@pytest.fixture(autouse=True)
def _fresh_db(tmp_path, monkeypatch):
"""Use a temporary database for every test."""
monkeypatch.setenv("SKIPREDICTOR_DB_PATH", str(tmp_path / "test.db"))
# Force re-import to pick up new path
from storage import sqlite_store
sqlite_store.DEFAULT_DB_PATH = tmp_path / "test.db"
def _register(email: str = _TEST_EMAIL, password: str = _TEST_PASSWORD):
return client.post(
"/api/v1/auth/register",
json={"email": email, "password": password},
)
def _login(email: str = _TEST_EMAIL, password: str = _TEST_PASSWORD):
return client.post(
"/api/v1/auth/login",
data={"username": email, "password": password},
)
def _auth_header(token: str) -> dict:
return {"Authorization": f"Bearer {token}"}
# -- Tests ------------------------------------------------------------------
def test_register_and_login():
"""Register a user, then login to get a token."""
resp = _register()
assert resp.status_code == 201
data = resp.json()
assert data["email"] == _TEST_EMAIL
assert "id" in data
resp = _login()
assert resp.status_code == 200
data = resp.json()
assert "access_token" in data
assert data["token_type"] == "bearer"
def test_duplicate_email_returns_409():
"""Registering the same email twice returns 409."""
_register()
resp = _register()
assert resp.status_code == 409
def test_protected_endpoint_without_token_returns_401():
"""Accessing a protected endpoint without a token returns 401."""
resp = client.get("/api/v1/stations")
assert resp.status_code == 401
def test_protected_endpoint_with_valid_token():
"""Accessing a protected endpoint with a valid token succeeds."""
_register()
token = _login().json()["access_token"]
resp = client.get("/api/v1/stations", headers=_auth_header(token))
assert resp.status_code == 200
def test_health_stays_public():
"""/health does not require authentication."""
resp = client.get("/api/v1/health")
assert resp.status_code == 200
def test_invalid_token_returns_401():
"""A malformed token returns 401."""
resp = client.get(
"/api/v1/stations",
headers=_auth_header("not.a.valid.token"),
)
assert resp.status_code == 401
def test_wrong_password_returns_401():
"""Login with wrong password returns 401."""
_register()
resp = _login(password="wrongpassword1")
assert resp.status_code == 401
def test_login_nonexistent_user_returns_401():
"""Login with an email that doesn't exist returns 401."""
resp = _login(email="nobody@example.com")
assert resp.status_code == 401