from django.test import TestCase
from typing import List
from django_components.util.html_parser import HTMLTag, _parse_html as parse_html, set_html_attributes
from .django_test_setup import setup_test_config
setup_test_config({"autodiscover": False})
# This same set of tests is also found in djc_html_parser, to ensure that
# this implementation can be replaced with the djc_html_parser's Rust-based implementation
class TestHTMLParser(TestCase):
def test_basic_transformation(self):
html = "
"""
assert result == expected
# Verify attribute capturing
assert len(captured) == 3
# Root element should have both root and all attributes
assert captured["123"] == ["data-root", "data-v-123"]
# Non-root elements should only have all attributes
assert captured["456"] == ["data-v-123"]
assert captured["789"] == ["data-v-123"]
def test_whitespace_preservation(self):
html = """
"""
assert result == expected
# This checks that the parser works irrespective of the main use case
class TestHTMLParserInternal(TestCase):
def test_parse_simple_tag(self):
processed_tags = []
def on_tag(tag: HTMLTag, tag_stack: List[HTMLTag]) -> None:
processed_tags.append(tag)
html = "
"""
result = parse_html(html, on_tag)
self.assertEqual(result, expected)
# Verify the structure of processed tags
self.assertEqual(len(processed_tags), 12) # Count all non-void elements
# Verify specific tag attributes
html_tag = next(tag for tag in processed_tags if tag.name == "html")
self.assertEqual(len(html_tag.attrs), 2)
self.assertEqual(html_tag.attrs[0].key, "lang")
self.assertEqual(html_tag.attrs[0].value, "en")
self.assertEqual(html_tag.attrs[1].key, "data-theme")
self.assertEqual(html_tag.attrs[1].value, "light")
# Verify void elements
img_tag = next(tag for tag in processed_tags if tag.name == "img")
self.assertEqual(len(img_tag.attrs), 2)
self.assertEqual(img_tag.attrs[0].key, "src")
self.assertEqual(img_tag.attrs[0].value, "test.jpg")
# Verify attribute without value
body_tag = next(tag for tag in processed_tags if tag.name == "body")
data_loaded_attr = next(attr for attr in body_tag.attrs if attr.key == "data-loaded")
self.assertIsNone(data_loaded_attr.value)
# Verify modified attributes
self.assertTrue(any(attr.key == "data-modified" and attr.value == "true" for attr in body_tag.attrs))
self.assertTrue(any(attr.key == "className" and attr.value == "main" for attr in body_tag.attrs))
# Verify p tag modifications
p_tag = next(tag for tag in processed_tags if tag.name == "p")
self.assertTrue(any(attr.key == "hidden" and attr.value is None for attr in p_tag.attrs))