import re import pytest from django.contrib.auth import get_user_model from django.urls import reverse from apps.articles.models import STARRED_TAG_NAME, Article, ArticleTag, UserArticleState from apps.feeds.models import Feed, Subscription User = get_user_model() @pytest.fixture def alice(db): return User.objects.create_user("alice", password="pw-alice-123") @pytest.fixture def bob(db): return User.objects.create_user("bob", password="pw-bob-123") @pytest.fixture def alices_article(alice): feed = Feed.objects.create(feed_url="https://example.com/feed.xml", title="Example") Subscription.objects.create(user=alice, feed=feed) return Article.objects.create(feed=feed, guid="guid-1", title="Hello world") @pytest.mark.django_db def test_stream_requires_login(client): response = client.get(reverse("reader:stream")) assert response.status_code == 302 @pytest.mark.django_db def test_stream_shows_only_own_subscriptions(client, alice, bob, alices_article): client.login(username="bob", password="pw-bob-123") response = client.get(reverse("reader:stream")) assert alices_article.title not in response.content.decode() client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream")) assert alices_article.title in response.content.decode() @pytest.mark.django_db def test_unread_filter_excludes_read_articles(client, alice, alices_article): UserArticleState.objects.create(user=alice, article=alices_article, is_read=True) client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream"), {"filter": "unread"}) assert alices_article.title not in response.content.decode() response = client.get(reverse("reader:stream"), {"filter": "all"}) assert alices_article.title in response.content.decode() @pytest.mark.django_db def test_hidden_articles_are_excluded_from_every_filter(client, alice, alices_article): UserArticleState.objects.create(user=alice, article=alices_article, is_hidden=True) client.login(username="alice", password="pw-alice-123") for active_filter in ["unread", "all"]: response = client.get(reverse("reader:stream"), {"filter": active_filter}) assert alices_article.title not in response.content.decode() @pytest.mark.django_db def test_viewing_article_detail_marks_it_read(client, alice, alices_article): client.login(username="alice", password="pw-alice-123") assert not UserArticleState.objects.filter(user=alice, article=alices_article).exists() response = client.get(reverse("reader:article_detail", args=[alices_article.pk])) assert response.status_code == 200 state = UserArticleState.objects.get(user=alice, article=alices_article) assert state.is_read is True assert state.read_at is not None @pytest.mark.django_db def test_user_cannot_view_another_users_article(client, alice, bob, alices_article): client.login(username="bob", password="pw-bob-123") response = client.get(reverse("reader:article_detail", args=[alices_article.pk])) assert response.status_code == 404 @pytest.mark.django_db def test_toggle_star_flips_state_and_persists(client, alice, alices_article): client.login(username="alice", password="pw-alice-123") url = reverse("reader:toggle_star", args=[alices_article.pk]) response = client.post(url) assert response.status_code == 200 assert ArticleTag.objects.filter( user=alice, article=alices_article, tag__is_system=True, tag__name=STARRED_TAG_NAME, ).exists() client.post(url) assert not ArticleTag.objects.filter( user=alice, article=alices_article, tag__is_system=True, tag__name=STARRED_TAG_NAME, ).exists() @pytest.mark.django_db def test_toggle_read_requires_post(client, alice, alices_article): client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:toggle_read", args=[alices_article.pk])) assert response.status_code == 405 @pytest.mark.django_db def test_user_cannot_toggle_state_on_another_users_article(client, alice, bob, alices_article): client.login(username="bob", password="pw-bob-123") response = client.post(reverse("reader:toggle_star", args=[alices_article.pk])) assert response.status_code == 404 assert not UserArticleState.objects.filter(article=alices_article).exists() @pytest.mark.django_db def test_stream_remembers_last_selected_filter(client, alice, alices_article): from apps.articles.models import get_system_tag ArticleTag.objects.create( user=alice, article=alices_article, tag=get_system_tag(alice, STARRED_TAG_NAME) ) client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream"), {"filter": "starred"}) assert response.context["active_filter"] == "starred" # No ?filter= this time — e.g. a sidebar feed/tag link, or just "/" — # should fall back to "starred" rather than resetting to "unread". response = client.get(reverse("reader:stream")) assert response.context["active_filter"] == "starred" @pytest.mark.django_db def test_tag_filter_includes_articles_from_a_tagged_feed(client, alice, alices_article): from apps.articles.models import SubscriptionTag, Tag from apps.feeds.models import Subscription client.login(username="alice", password="pw-alice-123") tag = Tag.objects.create(user=alice, name="backend") subscription = Subscription.objects.get(user=alice, feed=alices_article.feed) SubscriptionTag.objects.create(user=alice, subscription=subscription, tag=tag) response = client.get(reverse("reader:stream"), {"filter": "all", "tag": tag.pk}) assert alices_article.title in response.content.decode() @pytest.mark.django_db def test_saved_filter_only_shows_saved_articles(client, alice, alices_article): client.login(username="alice", password="pw-alice-123") client.post(reverse("reader:toggle_saved", args=[alices_article.pk])) response = client.get(reverse("reader:stream"), {"filter": "saved"}) assert alices_article.title in response.content.decode() response = client.get(reverse("reader:stream"), {"filter": "starred"}) assert alices_article.title not in response.content.decode() @pytest.mark.django_db def test_sidebar_shows_a_tags_total_unread_count(client, alice): from apps.articles.models import SubscriptionTag, Tag feed_a = Feed.objects.create(feed_url="https://a.example.com/feed.xml") feed_b = Feed.objects.create(feed_url="https://b.example.com/feed.xml") sub_a = Subscription.objects.create(user=alice, feed=feed_a) sub_b = Subscription.objects.create(user=alice, feed=feed_b) tag = Tag.objects.create(user=alice, name="work") SubscriptionTag.objects.create(user=alice, subscription=sub_a, tag=tag) SubscriptionTag.objects.create(user=alice, subscription=sub_b, tag=tag) for i in range(3): Article.objects.create(feed=feed_a, guid=f"a-{i}", title=f"A{i}") for i in range(4): Article.objects.create(feed=feed_b, guid=f"b-{i}", title=f"B{i}") client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream")) # The only "7" on the page — the individual feeds show 3 and 4. assert sorted(_visible_counts(response.content.decode())) == ["3", "4", "7"] @pytest.mark.django_db def test_article_rows_carry_their_utc_instant_for_client_side_date_grouping(client, alice): """The server still groups date headers in UTC, but ships each row's raw UTC instant so date-groups.js can rebuild the headers using the viewer's local calendar day instead.""" from django.utils import timezone feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) dated = Article.objects.create( feed=feed, guid="dated", title="Dated", published_at=timezone.now() ) undated = Article.objects.create(feed=feed, guid="undated", title="No publish date") client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream"), {"filter": "all"}) content = response.content.decode() expected_iso = dated.published_at.isoformat() assert f'id="article-{dated.pk}"' in content assert f'data-published-utc="{expected_iso}"' in content # A feed that gave no publish date falls back to when it was fetched # (the same fallback the stream's sort order uses), so the row still # carries a time and groups under a real date, not "Undated". undated_row = re.search(rf'
  • ', content, flags=re.DOTALL) assert undated_row is not None row_html = undated_row.group(0) assert f'data-published-utc="{undated.fetched_at.isoformat()}"' in row_html assert 'class="article-time"' in row_html assert "Undated" not in content @pytest.mark.django_db def test_pages_render_the_banner_placeholder_and_baseline_for_any_scope(client, alice): """The banner lives in the base layout with the page's baseline id rendered in, so it works under any feed/tag selection (and on pages that aren't the stream), not only the unscoped list.""" feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create(feed=feed, guid="g1", title="Hello") client.login(username="alice", password="pw-alice-123") for query in ({"filter": "all"}, {"feed": feed.pk}): content = client.get(reverse("reader:stream"), query).content.decode() assert 'class="new-articles-banner"' in content assert f'data-since="{article.pk}"' in content other_page = client.get(reverse("feeds:subscription_list")).content.decode() assert 'class="new-articles-banner"' in other_page @pytest.mark.django_db def test_new_since_counts_new_articles_outside_the_page_s_own_feed(client, alice): """The banner for a page showing feed A still reports a new article in feed B — the poll isn't scoped to the selected feed or tag.""" from apps.articles.models import SubscriptionTag, Tag feed_a = Feed.objects.create(feed_url="https://a.example.com/feed.xml") feed_b = Feed.objects.create(feed_url="https://b.example.com/feed.xml") sub_a = Subscription.objects.create(user=alice, feed=feed_a) Subscription.objects.create(user=alice, feed=feed_b) tag = Tag.objects.create(user=alice, name="work") SubscriptionTag.objects.create(user=alice, subscription=sub_a, tag=tag) cursor = Article.objects.create(feed=feed_a, guid="cursor", title="Cursor").pk Article.objects.create(feed=feed_b, guid="untagged-new", title="Untagged new") client.login(username="alice", password="pw-alice-123") body = client.get(reverse("reader:new_since"), {"since": cursor}).json() assert body["new_count"] == 1 @pytest.mark.django_db def test_new_since_returns_current_sidebar_counts(client, alice): from apps.articles.models import SubscriptionTag, Tag feed = Feed.objects.create(feed_url="https://a.example.com/feed.xml") sub = Subscription.objects.create(user=alice, feed=feed) tag = Tag.objects.create(user=alice, name="work") SubscriptionTag.objects.create(user=alice, subscription=sub, tag=tag) for i in range(3): Article.objects.create(feed=feed, guid=f"g{i}", title=f"T{i}") client.login(username="alice", password="pw-alice-123") counts = client.get(reverse("reader:new_since"), {"since": 0}).json()["counts"] assert counts == {"feeds": {str(feed.pk): 3}, "tags": {str(tag.pk): 3}, "starred": 0} @pytest.mark.django_db @pytest.mark.parametrize( "url_name, uses_article", [("reader:toggle_read", True), ("reader:toggle_star", True), ("reader:article_inline", True)], ) def test_actions_that_change_counts_tell_the_page_to_refresh_them( client, alice, url_name, uses_article ): feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create(feed=feed, guid="a-1", title="Hello") client.login(username="alice", password="pw-alice-123") url = reverse(url_name, args=[article.pk]) response = client.get(url) if url_name == "reader:article_inline" else client.post(url) assert response["HX-Trigger"] == "countsChanged" def _visible_counts(content): """Texts of the sidebar count badges that are actually shown.""" return re.findall( r'(\d+)', content ) @pytest.mark.django_db def test_sidebar_count_is_fresh_right_after_new_articles_are_ingested(client, alice): """Ingestion drops the cached counts, so the next render (and the next poll) shows new articles at once instead of after the cache TTL.""" from apps.core.cache_utils import invalidate_feed_subscribers_sidebar_cache feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) Article.objects.create(feed=feed, guid="a-1", title="One") client.login(username="alice", password="pw-alice-123") assert _visible_counts(client.get(reverse("reader:stream")).content.decode()) == ["1"] Article.objects.create(feed=feed, guid="a-2", title="Two") assert _visible_counts(client.get(reverse("reader:stream")).content.decode()) == ["1"] invalidate_feed_subscribers_sidebar_cache(feed.pk) assert _visible_counts(client.get(reverse("reader:stream")).content.decode()) == ["2"] @pytest.mark.django_db def test_new_subscription_shows_its_count_without_waiting_for_the_cache(client, alice): feed_a = Feed.objects.create(feed_url="https://a.example.com/feed.xml") feed_b = Feed.objects.create(feed_url="https://b.example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed_a) Article.objects.create(feed=feed_a, guid="a", title="A") Article.objects.create(feed=feed_b, guid="b", title="B") client.login(username="alice", password="pw-alice-123") client.get(reverse("reader:stream")) Subscription.objects.create(user=alice, feed=feed_b) assert sorted(_visible_counts(client.get(reverse("reader:stream")).content.decode())) == [ "1", "1", ] @pytest.mark.django_db def test_sidebar_unread_count_updates_immediately_after_reading_an_article(client, alice): """unread_counts_by_feed caches its result for a short TTL (C3) — the reader views that change the current user's own read state must invalidate it, or the sidebar would show a stale count until the TTL elapses on every one of these very common actions.""" feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create(feed=feed, guid="a-1", title="Hello") client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream")) assert _visible_counts(response.content.decode()) == ["1"] client.get(reverse("reader:article_detail", args=[article.pk])) response = client.get(reverse("reader:stream")) assert _visible_counts(response.content.decode()) == [] @pytest.mark.django_db def test_sidebar_unread_count_updates_immediately_after_toggle_read(client, alice): feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create(feed=feed, guid="a-1", title="Hello") UserArticleState.objects.create(user=alice, article=article, is_read=True) client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream")) assert _visible_counts(response.content.decode()) == [] client.post(reverse("reader:toggle_read", args=[article.pk])) response = client.get(reverse("reader:stream")) assert _visible_counts(response.content.decode()) == ["1"] @pytest.mark.django_db def test_sidebar_unread_count_updates_immediately_after_mark_all_read(client, alice): feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) Article.objects.create(feed=feed, guid="a-1", title="Hello") client.login(username="alice", password="pw-alice-123") response = client.get(reverse("reader:stream")) assert _visible_counts(response.content.decode()) == ["1"] client.post(reverse("reader:mark_all_read")) response = client.get(reverse("reader:stream")) assert _visible_counts(response.content.decode()) == [] def _stream_article_ids(client, query): response = client.get(reverse("reader:stream"), query) content = response.content.decode() ids = [int(m) for m in re.findall(r'
  • {label}', content) if not match: return None from urllib.parse import parse_qsl return dict(parse_qsl(match.group(1).replace("&", "&"))) @pytest.mark.django_db def test_stream_keyset_pagination_pages_through_tied_timestamps_without_gaps(client, alice): """Keyset pagination (C4) on (sort_at, id): articles sharing an exact timestamp must neither repeat nor go missing across page boundaries, which offset paging over a non-unique order can't guarantee.""" from django.utils import timezone from apps.reader.views import PAGE_SIZE feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) same_moment = timezone.now() total = PAGE_SIZE * 2 + 5 created = [ Article.objects.create(feed=feed, guid=f"g{i}", title=f"T{i}", published_at=same_moment) for i in range(total) ] client.login(username="alice", password="pw-alice-123") seen = [] query = {"filter": "all"} pages = 0 while query: ids, content = _stream_article_ids(client, query) assert len(ids) <= PAGE_SIZE seen.extend(ids) query = _link_query(content, "Older") pages += 1 assert pages < 10 assert pages == 3 assert len(seen) == total assert sorted(seen) == sorted(a.pk for a in created) @pytest.mark.django_db def test_stream_newer_link_returns_to_the_previous_page(client, alice): from django.utils import timezone from apps.reader.views import PAGE_SIZE feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) now = timezone.now() for i in range(PAGE_SIZE + 5): Article.objects.create( feed=feed, guid=f"g{i}", title=f"T{i}", published_at=now - timezone.timedelta(minutes=i), ) client.login(username="alice", password="pw-alice-123") first_ids, first_content = _stream_article_ids(client, {"filter": "all"}) assert _link_query(first_content, "Newer") is None second_ids, second_content = _stream_article_ids(client, _link_query(first_content, "Older")) assert len(second_ids) == 5 assert _link_query(second_content, "Older") is None back_ids, _ = _stream_article_ids(client, _link_query(second_content, "Newer")) assert back_ids == first_ids @pytest.mark.django_db def test_stream_pagination_links_keep_the_feed_scope(client, alice): from apps.reader.views import PAGE_SIZE feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) for i in range(PAGE_SIZE + 1): Article.objects.create(feed=feed, guid=f"g{i}", title=f"T{i}") client.login(username="alice", password="pw-alice-123") _, content = _stream_article_ids(client, {"filter": "all", "feed": feed.pk}) assert _link_query(content, "Older")["feed"] == str(feed.pk) def test_templates_use_no_inline_event_handlers(): """Production's CSP (script-src 'self') blocks inline on*= handlers — they work in dev, where no CSP is sent, and silently do nothing in production. Behavior belongs in static/js.""" from pathlib import Path from django.conf import settings pattern = re.compile(r"""<[^>]+\s(on[a-z]+)\s*=""", re.IGNORECASE) offenders = [] for template in Path(settings.BASE_DIR, "templates").rglob("*.html"): for match in pattern.finditer(template.read_text()): offenders.append(f"{template.name}: {match.group(1)}") assert offenders == [] @pytest.mark.django_db def test_article_detail_back_link_keeps_the_stream_scope(client, alice): feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create(feed=feed, guid="g1", title="Hello") client.login(username="alice", password="pw-alice-123") stream = client.get( reverse("reader:stream"), {"filter": "all", "feed": feed.pk} ).content.decode() link = re.search(r'href="(/articles/\d+/\?[^"]+)"', stream) assert link is not None detail = client.get(link.group(1).replace("&", "&")).content.decode() assert f"filter=all&feed={feed.pk}" in detail assert "Back to stream" in detail assert article.title in detail @pytest.mark.django_db def test_article_with_no_publish_date_shows_when_it_was_fetched(client, alice): """A feed that gives no date is treated as published when we fetched it — in the list row, its group header, and the open article's header — without storing an invented value on the article itself.""" feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create(feed=feed, guid="g1", title="No publish date") assert article.published_at is None client.login(username="alice", password="pw-alice-123") iso = article.fetched_at.isoformat() stream = client.get(reverse("reader:stream"), {"filter": "all"}).content.decode() assert f'datetime="{iso}"' in stream assert "Received today" in stream detail = client.get(reverse("reader:article_detail", args=[article.pk])).content.decode() assert f'datetime="{iso}"' in detail article.refresh_from_db() assert article.published_at is None @pytest.mark.django_db def test_new_since_requires_login(client): response = client.get(reverse("reader:new_since")) assert response.status_code == 302 @pytest.mark.django_db def test_new_since_without_a_cursor_returns_the_baseline_id(client, alice): feed = Feed.objects.create(feed_url="https://example.com/feed.xml") Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create(feed=feed, guid="g1", title="Hello") client.login(username="alice", password="pw-alice-123") body = client.get(reverse("reader:new_since")).json() assert body["latest_id"] == article.pk assert body["new_count"] == 0 @pytest.mark.django_db def test_new_since_counts_only_new_unread_visible_articles_from_my_feeds(client, alice, bob): mine = Feed.objects.create(feed_url="https://mine.example.com/feed.xml") theirs = Feed.objects.create(feed_url="https://theirs.example.com/feed.xml") Subscription.objects.create(user=alice, feed=mine) Subscription.objects.create(user=bob, feed=theirs) cursor = Article.objects.create(feed=mine, guid="cursor", title="Cursor").pk new_unread = Article.objects.create(feed=mine, guid="n1", title="New unread") already_read = Article.objects.create(feed=mine, guid="n2", title="New but read") hidden = Article.objects.create(feed=mine, guid="n3", title="New but hidden") Article.objects.create(feed=theirs, guid="n4", title="Someone else's feed") UserArticleState.objects.create(user=alice, article=already_read, is_read=True) UserArticleState.objects.create(user=alice, article=hidden, is_hidden=True) client.login(username="alice", password="pw-alice-123") body = client.get(reverse("reader:new_since"), {"since": cursor}).json() assert body["new_count"] == 1 assert new_unread.pk > cursor @pytest.mark.django_db def test_authenticated_pages_load_the_live_updates_script_with_its_endpoint(client, alice): client.login(username="alice", password="pw-alice-123") content = client.get(reverse("reader:stream")).content.decode() assert "js/live-updates" in content assert f'data-url="{reverse("reader:new_since")}"' in content client.logout() assert "live-updates" not in client.get(reverse("accounts:login")).content.decode() @pytest.mark.django_db def test_unsafe_stored_links_are_not_rendered_as_hrefs(client, alice, django_user_model): """R2-S1 render boundary: even if a bad URL is already in the database (stored before validation existed), it must not become a clickable javascript: link.""" feed = Feed.objects.create( feed_url="https://example.com/feed.xml", site_url="javascript:alert(1)" ) Subscription.objects.create(user=alice, feed=feed) article = Article.objects.create( feed=feed, guid="g1", title="Hello", link="javascript:alert(2)" ) client.login(username="alice", password="pw-alice-123") detail = client.get(reverse("reader:article_detail", args=[article.pk])).content.decode() assert "javascript:" not in detail assert "Original" not in detail article.link = "https://example.com/real" article.save() detail = client.get(reverse("reader:article_detail", args=[article.pk])).content.decode() assert 'href="https://example.com/real"' in detail django_user_model.objects.create_user("admin", password="pw-admin-123", is_staff=True) client.login(username="admin", password="pw-admin-123") Feed.objects.filter(pk=feed.pk).update(fetch_error_count=2, last_fetch_status="error") dashboard = client.get(reverse("core:dashboard")).content.decode() assert "javascript:" not in dashboard