From 1c7917cb866b4d086426e98cfe5f62a4b144a217 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Fri, 1 Jul 2022 08:55:42 +0100 Subject: [PATCH] Add tests for ToC generator --- website/common/tests.py | 66 ++++++++++++++++++++++++++++++++++++++++- website/common/utils.py | 4 +++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/website/common/tests.py b/website/common/tests.py index 660a769..d9d73fa 100644 --- a/website/common/tests.py +++ b/website/common/tests.py @@ -2,7 +2,7 @@ from django.test import SimpleTestCase from .embed import YouTubeLiteEmbedFinder from .models import BasePage -from .utils import get_page_models +from .utils import get_page_models, get_table_of_contents class BasePageTestCase(SimpleTestCase): @@ -28,3 +28,67 @@ class YouTubeLiteEmbedFinderTestCase(SimpleTestCase): ) with self.assertRaises(ValueError): YouTubeLiteEmbedFinder._get_video_id("something-else") + + +class TableOfContentsTestCase(SimpleTestCase): + def test_creates_table_of_contents(self) -> None: + toc = get_table_of_contents( + """ +

2

+

2.1

+

2.2

+

2.2.1

+

2.3

+

3

+

3.1

+

4

+ """ + ) + + self.assertEqual(len(toc), 3) + self.assertEqual([entry.title for entry in toc], ["2", "3", "4"]) + + first_entry = toc[0] + self.assertEqual(len(first_entry.children), 3) + self.assertEqual( + [entry.title for entry in first_entry.children], ["2.1", "2.2", "2.3"] + ) + + sub_entry = first_entry.children[1] + self.assertEqual(len(sub_entry.children), 1) + self.assertEqual([entry.title for entry in sub_entry.children], ["2.2.1"]) + + second_entry = toc[1] + self.assertEqual(len(second_entry.children), 1) + self.assertEqual([entry.title for entry in second_entry.children], ["3.1"]) + + def test_no_headings(self) -> None: + toc = get_table_of_contents("

I'm no heading

") + self.assertEqual(toc, []) + + def test_no_content(self) -> None: + toc = get_table_of_contents("") + self.assertEqual(toc, []) + + def test_non_sequential_headings(self) -> None: + toc = get_table_of_contents( + """ +

2

+

2.1

+

2.2

+
2.2.1
+

2.3

+ """ + ) + + self.assertEqual(len(toc), 1) + + first_entry = toc[0] + self.assertEqual(len(first_entry.children), 3) + self.assertEqual( + [entry.title for entry in first_entry.children], ["2.1", "2.2", "2.3"] + ) + + sub_entry = first_entry.children[1] + self.assertEqual(len(sub_entry.children), 1) + self.assertEqual([entry.title for entry in sub_entry.children], ["2.2.1"]) diff --git a/website/common/utils.py b/website/common/utils.py index 1e19d24..1fefd08 100644 --- a/website/common/utils.py +++ b/website/common/utils.py @@ -26,6 +26,10 @@ def get_table_of_contents(html: str) -> list[TocEntry]: TocEntry(tag.text, tag.text, int(tag.name[1]), []) for tag in headings ] + # Abort if there are no headings + if not heading_levels: + return [] + # Ensure heading levels are sequential for heading, next_heading in pairwise(heading_levels): if next_heading.level - heading.level > 1: