import pytest from django.contrib.auth import get_user_model from apps.core.cache_utils import invalidate_sidebar_unread_cache from apps.feeds.models import Feed, Subscription from .models import Article from .queries import unread_counts_by_feed User = get_user_model() @pytest.fixture def alice(db): return User.objects.create_user("alice", password="pw-alice-123") @pytest.fixture def feed(db): return Feed.objects.create(feed_url="https://example.com/feed.xml") @pytest.mark.django_db def test_unread_counts_by_feed_is_cached_across_calls(alice, feed): """unread_counts_by_feed (C3) caches its result — a second call right after a new unread article appears must still see the stale cached value until invalidated or the TTL elapses, proving it isn't recomputing the query every time.""" Subscription.objects.create(user=alice, feed=feed) Article.objects.create(feed=feed, guid="a-1") first = unread_counts_by_feed(alice) assert first == {feed.pk: 1} Article.objects.create(feed=feed, guid="a-2") second = unread_counts_by_feed(alice) assert second == {feed.pk: 1}, "expected the cached count, not a fresh recount" @pytest.mark.django_db def test_invalidate_sidebar_unread_cache_forces_a_recount(alice, feed): Subscription.objects.create(user=alice, feed=feed) Article.objects.create(feed=feed, guid="a-1") unread_counts_by_feed(alice) Article.objects.create(feed=feed, guid="a-2") invalidate_sidebar_unread_cache(alice.pk) assert unread_counts_by_feed(alice) == {feed.pk: 2} @pytest.mark.django_db def test_unread_counts_by_feed_cache_is_per_user(alice, feed): bob = User.objects.create_user("bob", password="pw-bob-123") Subscription.objects.create(user=alice, feed=feed) Subscription.objects.create(user=bob, feed=feed) Article.objects.create(feed=feed, guid="a-1") assert unread_counts_by_feed(alice) == {feed.pk: 1} assert unread_counts_by_feed(bob) == {feed.pk: 1}