From e8cd4f66287fc92dae8b83e917748e306f912799 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Fri, 2 Jun 2023 17:35:31 +0100 Subject: [PATCH] Add tests for post similarity --- website/blog/models.py | 4 ++-- website/blog/tests.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/website/blog/models.py b/website/blog/models.py index 1d38e28..b417082 100644 --- a/website/blog/models.py +++ b/website/blog/models.py @@ -97,8 +97,8 @@ class BlogPostPage(BaseContentPage): similar_posts = similar_posts.annotate( similarity=(models.F("tag_similarity") * 2) - * (models.F("title_similarity") * 10) - * (models.F("subtitle_similarity")) + + (models.F("title_similarity") * 10) + + (models.F("subtitle_similarity")) ).order_by("-similarity")[:3] return similar_posts diff --git a/website/blog/tests.py b/website/blog/tests.py index 4ec7c3b..626cc0b 100644 --- a/website/blog/tests.py +++ b/website/blog/tests.py @@ -21,6 +21,45 @@ class BlogPostPageTestCase(TestCase): self.client.get(self.page.url) +class BlogPostPageSimilarityTestCase(TestCase): + @classmethod + def setUpTestData(cls) -> None: + cls.home_page = HomePage.objects.get() + cls.blog_post_list_page = BlogPostListPageFactory(parent=cls.home_page) + cls.page = BlogPostPageFactory( + parent=cls.blog_post_list_page, title="Blog post 1" + ) + + cls.similar_page_1 = BlogPostPageFactory( + parent=cls.blog_post_list_page, title="Blog post 2" + ) + cls.similar_page_2 = BlogPostPageFactory( + parent=cls.blog_post_list_page, title="Blog post 3" + ) + cls.similar_page_3 = BlogPostPageFactory( + parent=cls.blog_post_list_page, title="Blog post 4" + ) + + BlogPostPageFactory(parent=cls.blog_post_list_page, title="Legal documents") + + def test_similar_pages(self) -> None: + self.assertEqual( + set(self.page.get_similar_posts()), + {self.similar_page_1, self.similar_page_2, self.similar_page_3}, + ) + + def test_page_similarity(self) -> None: + for page in self.page.get_similar_posts(): + self.assertNotEqual(page.similarity, 0.0) + + def test_ordered_by_similarity(self) -> None: + similar_pages = self.page.get_similar_posts() + self.assertEqual( + list(similar_pages), + sorted(similar_pages, key=lambda p: p.similarity, reverse=True), + ) + + class BlogPostListPageTestCase(TestCase): @classmethod def setUpTestData(cls) -> None: