Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
zerolab committed Feb 7, 2025
1 parent 0fc4423 commit e28dbe7
Show file tree
Hide file tree
Showing 9 changed files with 409 additions and 10 deletions.
4 changes: 2 additions & 2 deletions cms/articles/tests/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class HeadlineFigureBlockFactory(wagtail_factories.StructBlockFactory):
trend = wagtail_factories.CharBlockFactory()


class ArticleSeriesFactory(wagtail_factories.PageFactory):
class ArticleSeriesPageFactory(wagtail_factories.PageFactory):
"""Factory for ArticleSeriesPage."""

class Meta:
Expand All @@ -36,7 +36,7 @@ class Meta:
django_get_or_create: ClassVar[list[str]] = ["slug", "parent"]

title = factory.Faker("sentence", nb_words=4)
parent = factory.SubFactory(ArticleSeriesFactory)
parent = factory.SubFactory(ArticleSeriesPageFactory)

summary = factory.Faker("text", max_nb_chars=100)
news_headline = factory.Faker("text", max_nb_chars=50)
Expand Down
4 changes: 2 additions & 2 deletions cms/articles/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from django.utils.formats import date_format
from wagtail.test.utils import WagtailTestUtils

from cms.articles.tests.factories import ArticleSeriesFactory, StatisticalArticlePageFactory
from cms.articles.tests.factories import ArticleSeriesPageFactory, StatisticalArticlePageFactory
from cms.core.tests.factories import ContactDetailsFactory


Expand All @@ -16,7 +16,7 @@ class ArticleSeriesTestCase(WagtailTestUtils, TestCase):

@classmethod
def setUpTestData(cls):
cls.series = ArticleSeriesFactory()
cls.series = ArticleSeriesPageFactory()

def test_index_redirect_404_with_no_subpages(self):
"""Test index path redirects to latest."""
Expand Down
134 changes: 134 additions & 0 deletions cms/core/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
from datetime import datetime

from django.test import TestCase
from django.utils.formats import date_format

from cms.core.models.base import BasePage
from cms.core.utils import get_formatted_pages_list


# DummyPage mimics the minimum attributes and methods of a Wagtail Page.
class DummyPage(BasePage):
def __init__(self, title, summary="", listing_summary="", url="https://ons.gov.uk", **kwargs): # pylint: disable=super-init-not-called
# this just set attributes manually.
self.title = title
self.summary = summary
self.listing_summary = listing_summary
self._url = url
self._release_date = kwargs.get("release_date")

def get_url(self, request=None, current_site=None):
return self._url

@property
def release_date(self):
return self._release_date

class Meta:
abstract = True


class DummyPageWithNoReleaseDate(DummyPage):
@property
def label(self):
return "Dummy Page"

class Meta:
abstract = True


class GetFormattedPagesListTests(TestCase):
def test_without_release_date_and_listing_summary(self):
# When no listing_summary and release_date, should use summary for description,
# and use the default label.
page = DummyPage(title="Test Page", summary="Test summary", listing_summary="")
result = get_formatted_pages_list([page])
expected = {
"title": {"text": "Test Page", "url": "https://ons.gov.uk"},
"metadata": {"object": {"text": "Page"}},
"description": "Test summary",
}
self.assertEqual(len(result), 1)
self.assertDictEqual(result[0], expected)

def test_with_listing_summary_overrides_summary(self):
# When listing_summary is provided, that should be used as description.
page = DummyPage(title="Test Page", summary="Test summary", listing_summary="Listing summary")
result = get_formatted_pages_list([page])
expected = {
"title": {"text": "Test Page", "url": "https://ons.gov.uk"},
"metadata": {"object": {"text": "Page"}},
"description": "Listing summary",
}
self.assertEqual(len(result), 1)
self.assertDictEqual(result[0], expected)

def test_with_custom_label(self):
# When a custom label is defined, it should be used in metadata.
page = DummyPageWithNoReleaseDate(title="Test Page", summary="Test summary", listing_summary="")
result = get_formatted_pages_list([page])
expected = {
"title": {"text": "Test Page", "url": "https://ons.gov.uk"},
"metadata": {"object": {"text": "Dummy Page"}},
"description": "Test summary",
}
self.assertEqual(len(result), 1)
self.assertDictEqual(result[0], expected)

def test_with_release_date(self):
# When release_date is provided, metadata should include date formatting.
test_date = datetime(2024, 1, 1, 12, 30)
page = DummyPage(title="Test Page", summary="Test summary", listing_summary="", release_date=test_date)
result = get_formatted_pages_list([page])

expected_iso = date_format(test_date, "c")
expected_short = date_format(test_date, "DATE_FORMAT")

expected = {
"title": {"text": "Test Page", "url": "https://ons.gov.uk"},
"metadata": {
"object": {"text": "Page"},
"date": {
"prefix": "Released",
"showPrefix": True,
"iso": expected_iso,
"short": expected_short,
},
},
"description": "Test summary",
}
self.assertEqual(len(result), 1)
self.assertDictEqual(result[0], expected)

def test_multiple_pages(self):
# Test processing multiple dummy pages
test_date = datetime(2024, 1, 1, 12, 30)
page1 = DummyPage(title="Page One", summary="Summary One", listing_summary="", release_date=test_date)
page2 = DummyPageWithNoReleaseDate(title="Page Two", summary="Summary Two", listing_summary="Listing Two")
pages = [page1, page2]
result = get_formatted_pages_list(pages)

expected_iso = date_format(test_date, "c")
expected_short = date_format(test_date, "DATE_FORMAT")

expected_page1 = {
"title": {"text": "Page One", "url": "https://ons.gov.uk"},
"metadata": {
"object": {"text": "Page"},
"date": {
"prefix": "Released",
"showPrefix": True,
"iso": expected_iso,
"short": expected_short,
},
},
"description": "Summary One",
}
expected_page2 = {
"title": {"text": "Page Two", "url": "https://ons.gov.uk"},
"metadata": {"object": {"text": "Dummy Page"}},
"description": "Listing Two",
}
self.assertEqual(len(result), 2)
self.assertDictEqual(result[0], expected_page1)
self.assertDictEqual(result[1], expected_page2)
6 changes: 3 additions & 3 deletions cms/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ def get_formatted_pages_list(
},
"description": getattr(page, "listing_summary", "") or getattr(page, "summary", ""),
}
if hasattr(page, "release_date"):
if release_date := page.release_date:
datum["metadata"]["date"] = {
"prefix": _("Released"),
"showPrefix": True,
"iso": date_format(page.release_date, "c"),
"short": date_format(page.release_date, "DATE_FORMAT"),
"iso": date_format(release_date, "c"),
"short": date_format(release_date, "DATE_FORMAT"),
}
data.append(datum)
return data
3 changes: 1 addition & 2 deletions cms/topics/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ def get_formatted_value(self, value: "StructValue", context: dict | None = None)
},
"description": value["description"] or getattr(page, "listing_summary", "") or getattr(page, "summary", ""),
}
image = value["thumbnail"] or page.listing_image
if image:
if image := (value["thumbnail"] or getattr(page, "listing_image", None)):
renditions = image.get_renditions("fill-144x100", "fill-288x200")
formatted_value["thumbnail"] = {
"smallSrc": renditions["fill-144x100"].url,
Expand Down
Empty file added cms/topics/tests/__init__.py
Empty file.
20 changes: 19 additions & 1 deletion cms/topics/tests/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import wagtail_factories

from cms.themes.tests.factories import ThemePageFactory
from cms.topics.models import TopicPage
from cms.topics.models import TopicPage, TopicPageRelatedArticle, TopicPageRelatedMethodology


class TopicPageFactory(wagtail_factories.PageFactory):
Expand All @@ -14,3 +14,21 @@ class Meta:
title = factory.Faker("sentence", nb_words=4)
summary = factory.Faker("text", max_nb_chars=100)
parent = factory.SubFactory(ThemePageFactory)


class TopicPageRelatedArticleFactory(factory.django.DjangoModelFactory):
class Meta:
model = TopicPageRelatedArticle

parent = factory.SubFactory(TopicPageFactory)
page = factory.SubFactory("cms.articles.tests.factories.StatisticalArticlePageFactory")
sort_order = factory.Sequence(lambda n: n)


class TopicPageRelatedMethodologyFactory(factory.django.DjangoModelFactory):
class Meta:
model = TopicPageRelatedMethodology

parent = factory.SubFactory(TopicPageFactory)
page = factory.SubFactory("cms.methodology.tests.factories.MethodologyPageFactory")
sort_order = factory.Sequence(lambda n: n)
106 changes: 106 additions & 0 deletions cms/topics/tests/test_blocks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
from django.test import TestCase
from wagtail.images.tests.utils import get_test_image_file

from cms.home.models import HomePage
from cms.images.models import CustomImage
from cms.themes.tests.factories import ThemePageFactory
from cms.topics.blocks import ExploreMoreExternalLinkBlock, ExploreMoreInternalLinkBlock, ExploreMoreStoryBlock
from cms.topics.tests.factories import TopicPageFactory


class ExploreMoreBlocksTestCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.home_page = HomePage.objects.first()
cls.theme_page = ThemePageFactory(listing_summary="Theme summary")
cls.topic_page = TopicPageFactory(parent=cls.theme_page, live=False)

cls.image = CustomImage.objects.create(title="Test Image", file=get_test_image_file())

def test_external_link_block__get_formatted_value(self):
block = ExploreMoreExternalLinkBlock()
value = block.to_python(
{
"url": "https://ons.gov.uk",
"title": "External Link",
"description": "Test description",
"thumbnail": self.image.pk,
}
)

formatted = block.get_formatted_value(value)

self.assertEqual(formatted["title"]["text"], "External Link")
self.assertEqual(formatted["title"]["url"], "https://ons.gov.uk")
self.assertEqual(formatted["description"], "Test description")
self.assertIn("smallSrc", formatted["thumbnail"])
self.assertIn("largeSrc", formatted["thumbnail"])

def test_internal_link_block__get_formatted_value_with_overrides(self):
block = ExploreMoreInternalLinkBlock()
value = block.to_python(
{
"page": self.home_page.pk,
"title": "Custom Title",
"description": "Custom Description",
"thumbnail": self.image.pk,
}
)

formatted = block.get_formatted_value(value)

self.assertEqual(formatted["title"]["text"], "Custom Title")
self.assertEqual(formatted["description"], "Custom Description")
self.assertIn("smallSrc", formatted["thumbnail"])

def test_internal_link_block__get_formatted_value_without_overrides(self):
block = ExploreMoreInternalLinkBlock()
value = block.to_python({"page": self.home_page.pk, "title": "", "description": "", "thumbnail": None})

# Add page attributes that would normally exist
self.home_page.listing_summary = "Page listing summary"
self.home_page.listing_image = self.image
self.home_page.save()

formatted = block.get_formatted_value(value)

self.assertEqual(formatted["title"]["text"], self.home_page.title)
self.assertEqual(formatted["description"], "Page listing summary")
self.assertIn("smallSrc", formatted["thumbnail"])

def test_internal_link_block__get_formatted_value_with_unpublished_page_returns_empty(self):
block = ExploreMoreInternalLinkBlock()
value = block.to_python({"page": self.topic_page.pk})

self.assertEqual(block.get_formatted_value(value), {})

def test_explore_more_storyblock__get_context(self):
block = ExploreMoreStoryBlock()

# Create stream value with valid and invalid items
stream_value = block.to_python(
[
{
"type": "external_link",
"value": {
"url": "https://ons.gov.uk",
"title": "External",
"description": "Test",
"thumbnail": self.image.pk,
},
},
{"type": "internal_link", "value": {"page": self.theme_page.pk}},
{"type": "internal_link", "value": {"page": self.topic_page.pk}},
]
)

context = block.get_context(stream_value)
formatted_items = context["formatted_items"]

# Should only contain the valid external link
self.assertEqual(len(formatted_items), 2)
self.assertEqual(formatted_items[0]["title"]["text"], "External")
self.assertIn("thumbnail", formatted_items[0])

self.assertEqual(formatted_items[1]["title"]["text"], self.theme_page.title)
self.assertEqual(formatted_items[1]["description"], self.theme_page.listing_summary)
Loading

0 comments on commit e28dbe7

Please sign in to comment.