Files
newz-qwen-27b/backend/tests/test_models.py
T
Daniel Samson b186d0f797 feat: add JWT authentication with auth pages and tests (M5)
Backend (FastAPI):
- core/auth.py: PBKDF2-HMAC-SHA256 password hashing (120k iterations,
  random salt), HS256 JWT creation/verification (7-day expiry,
  HN_SECRET_KEY via config) and get_current_user Bearer dependency
- models/user.py: User model (username unique/indexed, password_hash,
  created_at); schemas/auth.py: register/login/token/user schemas
- api/v1/auth.py: POST /api/v1/auth/register (201), /login, /logout
  (204), GET /me; 400 on duplicate username, 401 on bad credentials,
  invalid/expired/unknown tokens
- requirements: PyJWT; env templates + docker-compose expose
  HN_SECRET_KEY (dev default, override in production)
- tests: 24 new backend tests (hashing, tokens, all endpoints)

Frontend (React + TypeScript):
- api/client.ts: AUTH_TOKEN localStorage persistence, automatic
  Bearer token attachment, 401 clears the stored token, typed
  login/register/logout/me helpers
- auth.tsx: AuthProvider (session restore + login/register/logout)
  and RequireAuth route guard
- pages: Login, Register, SignOut and a protected /account
  placeholder; header shows sign-in/register or user/sign-out
- styles: auth component classes in globals.css
- tests: unit tests for the client, provider and pages; Playwright
  E2E spec covering register/login/logout, session restore, invalid
  token cleanup and protected-route redirects (API mocked)

Note: the milestone's /api/auth/* paths map to the project's
established /api/v1/* prefix (see M2); the HN_SECRET_KEY default is
newzy-dev-secret-change-me.
2026-10-30 17:03:00 +00:00

157 lines
5.6 KiB
Python

"""Tests for ORM model instantiation and database operations."""
import pytest
from sqlalchemy.exc import IntegrityError
from models import Article, Author, Category, User, slugify
class TestAuthor:
def test_create_and_commit(self, session) -> None:
author = Author(
name="Ada Lovelace", email="ada@example.com", bio="First programmer."
)
session.add(author)
session.commit()
session.refresh(author)
assert author.id is not None
assert session.get(Author, author.id).email == "ada@example.com"
def test_unique_name_enforced(self, session) -> None:
session.add(Author(name="Grace Hopper", email="grace@example.com"))
session.commit()
session.add(Author(name="Grace Hopper", email="other@example.com"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_unique_email_enforced(self, session) -> None:
session.add(Author(name="Grace Hopper", email="grace@example.com"))
session.commit()
session.add(Author(name="Another Person", email="grace@example.com"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_bio_is_nullable(self, session) -> None:
author = Author(name="Alan Turing", email="alan@example.com")
session.add(author)
session.commit()
session.refresh(author)
assert author.bio is None
class TestUser:
def test_create_and_commit(self, session) -> None:
user = User(username="alice", password_hash="abc$def")
session.add(user)
session.commit()
session.refresh(user)
assert user.id is not None
assert user.created_at is not None
assert session.get(User, user.id).username == "alice"
def test_unique_username_enforced(self, session) -> None:
session.add(User(username="alice", password_hash="abc$def"))
session.commit()
session.add(User(username="alice", password_hash="other$hash"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
class TestCategory:
def test_create_and_commit(self, session) -> None:
category = Category(name="Technology", slug="technology")
session.add(category)
session.commit()
session.refresh(category)
assert category.id is not None
assert session.get(Category, category.id).name == "Technology"
def test_unique_name_enforced(self, session) -> None:
session.add(Category(name="Science", slug="science"))
session.commit()
session.add(Category(name="Science", slug="science-2"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_unique_slug_enforced(self, session) -> None:
session.add(Category(name="Science", slug="science"))
session.commit()
session.add(Category(name="Science News", slug="science"))
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_slug_generation(self) -> None:
assert slugify("Technology & Science") == "technology-science"
assert slugify(" Sports ") == "sports"
assert slugify("Already-fine") == "already-fine"
assert slugify("Café News") == "cafe-news"
class TestArticle:
def _make_author_category(self, session) -> tuple[Author, Category]:
author = Author(name="Byline Writer", email="writer@example.com")
category = Category(name="World", slug="world")
session.add_all([author, category])
session.commit()
session.refresh(author)
session.refresh(category)
return author, category
def test_create_and_commit(self, session) -> None:
author, category = self._make_author_category(session)
article = Article(
title="First post",
content="Hello world.",
author_id=author.id,
category_id=category.id,
)
session.add(article)
session.commit()
session.refresh(article)
assert article.id is not None
assert article.created_at is not None
assert article.published is False
def test_foreign_key_relationships(self, session) -> None:
author, category = self._make_author_category(session)
article = Article(
title="Related",
content="Body text.",
author_id=author.id,
category_id=category.id,
)
session.add(article)
session.commit()
assert article.author.name == author.name
assert article.category.slug == "world"
assert article in author.articles
assert article in category.articles
def test_unique_title_enforced(self, session) -> None:
author, category = self._make_author_category(session)
session.add(
Article(title="Dup", content="one", author_id=author.id, category_id=category.id)
)
session.commit()
session.add(
Article(title="Dup", content="two", author_id=author.id, category_id=category.id)
)
with pytest.raises(IntegrityError):
session.commit()
session.rollback()
def test_foreign_key_enforced(self, session) -> None:
author, category = self._make_author_category(session)
article = Article(
title="Orphan", content="No such author.", author_id=9999, category_id=category.id
)
session.add(article)
with pytest.raises(IntegrityError):
session.commit()
session.rollback()