Add tests for ToC generator

This commit is contained in:
Jake Howard 2022-07-01 08:55:42 +01:00
parent af2dba84cd
commit 1c7917cb86
Signed by: jake
GPG key ID: 57AFB45680EDD477
2 changed files with 69 additions and 1 deletions

View file

@ -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(
"""
<h2>2</h2>
<h3>2.1</h3>
<h3>2.2</h3>
<h4>2.2.1</h4>
<h3>2.3</h3>
<h2>3</h2>
<h3>3.1</h3>
<h2>4</h2>
"""
)
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("<p>I'm no heading</p>")
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(
"""
<h2>2</h2>
<h3>2.1</h3>
<h3>2.2</h3>
<h5>2.2.1</h5>
<h3>2.3</h3>
"""
)
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"])

View file

@ -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: