import pytest from django.contrib.auth import get_user_model from apps.feeds.models import Feed from .models import Article, Tag, UserArticleState User = get_user_model() @pytest.fixture def feed(db): return Feed.objects.create(feed_url="https://example.com/feed.xml", title="Example") @pytest.fixture def two_users(db): alice = User.objects.create_user("alice", password="pw-alice-123") bob = User.objects.create_user("bob", password="pw-bob-123") return alice, bob @pytest.mark.django_db def test_articles_dedup_by_feed_and_guid(feed): article, created = Article.objects.get_or_create( feed=feed, guid="guid-1", defaults={"title": "First version"} ) assert created # Re-ingesting the same guid (as the fetch pipeline would on a repeat # poll) must not create a second row. article_again, created_again = Article.objects.get_or_create( feed=feed, guid="guid-1", defaults={"title": "Should not be used"} ) assert not created_again assert article_again.pk == article.pk assert Article.objects.filter(feed=feed, guid="guid-1").count() == 1 @pytest.mark.django_db def test_user_article_state_is_lazy_and_per_user(feed, two_users): alice, bob = two_users article = Article.objects.create(feed=feed, guid="guid-1", title="Hello") # No state rows exist until someone interacts with the article. assert UserArticleState.objects.filter(article=article).count() == 0 UserArticleState.objects.create(user=alice, article=article, is_read=True) assert UserArticleState.objects.filter(article=article).count() == 1 alice_state = UserArticleState.objects.get(user=alice, article=article) assert alice_state.is_read is True # Bob has no row at all — he should be treated as unread, not as sharing # Alice's state. assert not UserArticleState.objects.filter(user=bob, article=article).exists() @pytest.mark.django_db def test_tags_are_scoped_per_user(two_users): alice, bob = two_users Tag.objects.create(user=alice, name="golang") Tag.objects.create(user=bob, name="golang") assert Tag.objects.filter(name="golang").count() == 2 with pytest.raises(Exception): Tag.objects.create(user=alice, name="golang") @pytest.mark.django_db def test_editing_article_content_does_not_touch_user_state(feed, two_users): alice, _ = two_users article = Article.objects.create(feed=feed, guid="guid-1", title="Original title") state = UserArticleState.objects.create(user=alice, article=article, is_read=True) # Simulate the fetch pipeline updating content on a re-fetch. article.title = "Updated title" article.save() state.refresh_from_db() assert state.is_read is True