"""Tests for the public article read API (``/api/v1/articles``). These endpoints power the site front end. They require no authentication, expose *published* articles only, and embed the related author/category so the front page can render full details from a single payload. """ from datetime import datetime, timedelta, timezone from models import Article, Author, Category BASE = "/api/v1/articles" def _make_author(session, name="Byline Writer", email="writer@example.com") -> Author: author = Author(name=name, email=email) session.add(author) session.commit() return author def _make_category(session, name="Technology", slug="technology") -> Category: category = Category(name=name, slug=slug) session.add(category) session.commit() return category def _make_article( session, title, author, category, published=True, created_at=None, ) -> Article: article = Article( title=title, content=f"
Body for {title}
", author_id=author.id, category_id=category.id, published=published, created_at=created_at or datetime.now(timezone.utc), ) session.add(article) session.commit() session.refresh(article) return article class TestListPublishedArticles: def test_requires_no_authentication(self, client, session) -> None: author = _make_author(session) category = _make_category(session) _make_article(session, "Public story", author, category) response = client.get(BASE) assert response.status_code == 200 def test_returns_only_published_newest_first(self, client, session) -> None: author = _make_author(session) category = _make_category(session) base = datetime(2025, 1, 1, tzinfo=timezone.utc) old = _make_article(session, "Old published", author, category, created_at=base) new = _make_article( session, "New published", author, category, created_at=base + timedelta(days=2) ) draft = _make_article( session, "Still a draft", author, category, published=False, created_at=base + timedelta(days=3), ) response = client.get(BASE) assert response.status_code == 200 body = response.json() assert [a["title"] for a in body] == ["New published", "Old published"] assert all(a["published"] is True for a in body) assert draft.id not in {a["id"] for a in body} def test_entry_embeds_author_and_category(self, client, session) -> None: author = _make_author(session, name="Amara Osei", email="amara@example.com") category = _make_category(session, name="Culture", slug="culture") article = _make_article(session, "Gallery nights", author, category) body = client.get(BASE).json() entry = body[0] assert entry["id"] == article.id assert entry["content"] == f"Body for {article.title}
" assert entry["author"] == { "id": author.id, "name": "Amara Osei", "email": "amara@example.com", "bio": None } assert entry["category"] == {"id": category.id, "name": "Culture", "slug": "culture"} def test_empty_when_nothing_published(self, client, session) -> None: author = _make_author(session) category = _make_category(session) _make_article(session, "Only a draft", author, category, published=False) assert client.get(BASE).json() == [] class TestGetPublishedArticle: def test_returns_published_article(self, client, session) -> None: author = _make_author(session) category = _make_category(session) article = _make_article(session, "The one", author, category) response = client.get(f"{BASE}/{article.id}") assert response.status_code == 200 body = response.json() assert body["id"] == article.id assert body["title"] == "The one" assert body["author"]["id"] == author.id assert body["category"]["id"] == category.id def test_draft_returns_404(self, client, session) -> None: author = _make_author(session) category = _make_category(session) draft = _make_article(session, "Hidden", author, category, published=False) response = client.get(f"{BASE}/{draft.id}") assert response.status_code == 404 assert response.json()["code"] == "not_found" def test_unknown_id_returns_404(self, client, session) -> None: response = client.get(f"{BASE}/9999") assert response.status_code == 404 assert response.json()["code"] == "not_found" class TestSeedContentScript: """The seeder creates the demo authors/categories/articles, idempotently.""" def _run_seed(self, session, monkeypatch) -> str: import seed_content monkeypatch.setattr(seed_content, "SessionLocal", lambda: session) assert seed_content.main() == 0 captured = __import__("io").StringIO() return captured.getvalue() def test_creates_demo_content(self, session, monkeypatch, capsys) -> None: import seed_content monkeypatch.setattr(seed_content, "SessionLocal", lambda: session) assert seed_content.main() == 0 out = capsys.readouterr().out assert session.query(Author).count() == 3 assert session.query(Category).count() == 4 articles = session.query(Article).all() assert len(articles) == 6 assert all(a.published is True for a in articles) # The feed is newest-first and every article resolves its relations. titles = [a.title for a in articles] assert titles[0] == "Inside the new wave of open-source language models" for article in articles: assert article.author.name assert article.category.slug assert "Created author 'Ada Lovelace'" in out assert "Done." in out def test_is_idempotent(self, session, monkeypatch, capsys) -> None: import seed_content monkeypatch.setattr(seed_content, "SessionLocal", lambda: session) assert seed_content.main() == 0 capsys.readouterr() # Capture the id (plain int) — main() closes the shared session, # detaching ORM instances. first_article_id = session.query(Article).first().id assert seed_content.main() == 0 out = capsys.readouterr().out # No duplicates on the second run; nothing was re-created. assert session.query(Author).count() == 3 assert session.query(Category).count() == 4 assert session.query(Article).count() == 6 assert session.query(Article).first().id == first_article_id assert "Created author" not in out assert "Created article" not in out