From 09107e5735342471977c2993ec81408a91850da8 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcode0919@users.noreply.github.com> Date: Tue, 4 Aug 2026 11:26:28 -0700 Subject: [PATCH] HTML/XML tag checker --- src/practical/html_parser.py | 64 ++++++++++++++++++++++++++ tests/practical/test_data/invalid.html | 10 ++++ tests/practical/test_data/valid.html | 10 ++++ tests/practical/test_html_parser.py | 35 ++++++++++++++ 4 files changed, 119 insertions(+) create mode 100644 src/practical/html_parser.py create mode 100644 tests/practical/test_data/invalid.html create mode 100644 tests/practical/test_data/valid.html create mode 100644 tests/practical/test_html_parser.py diff --git a/src/practical/html_parser.py b/src/practical/html_parser.py new file mode 100644 index 0000000..fe9d7ef --- /dev/null +++ b/src/practical/html_parser.py @@ -0,0 +1,64 @@ +from html.parser import HTMLParser + + +class HTMLValidator: + """Check whether HTML content is well-formed, i.e. every tag has a matching close tag. + + This only verifies tag balance/nesting via a streaming `html.parser.HTMLParser`, not + conformance to the actual HTML5 element vocabulary or content model — unknown tag names + (e.g. ``) are accepted as well-formed as long as they're properly closed. + """ + + @staticmethod + def validate_html(path: str) -> bool: + """Return True if the file at `path` is well-formed HTML, False otherwise. + + Reads and parses the file in chunks so memory use stays bounded regardless of file size. + """ + parser = TagChecker() + + try: + with open(path, "r", encoding="utf-8") as f: + while chunk := f.read(64000): + parser.feed(chunk) + parser.close() + except FileNotFoundError as e: + raise e + except ValueError: + return False + + return parser.tag_stack == [] + + @staticmethod + def validate_string(string: str) -> bool: + """Return True if `string` is well-formed HTML, False otherwise.""" + parser = TagChecker() + + try: + parser.feed(string) + parser.close() + except ValueError: + return False + return parser.tag_stack == [] + + +class TagChecker(HTMLParser): + """Tracks open tags on a stack, raising ValueError on any mismatched or unclosed tag.""" + + def __init__(self): + super().__init__() + self.tag_stack = [] + + def handle_starttag(self, tag, attrs): + self.tag_stack.append(tag) + + def handle_endtag(self, tag): + if not self.tag_stack or self.tag_stack[-1] != tag: + raise ValueError(f"Mismatched end tag: {tag}") + self.tag_stack.pop() + + def close(self): + """Flush any buffered data, then raise ValueError if any tags were left unclosed.""" + super().close() + if self.tag_stack: + raise ValueError(f"Unclosed tags: {self.tag_stack}") diff --git a/tests/practical/test_data/invalid.html b/tests/practical/test_data/invalid.html new file mode 100644 index 0000000..2169e54 --- /dev/null +++ b/tests/practical/test_data/invalid.html @@ -0,0 +1,10 @@ + + + Test + + +

Hello, World! +
+ Example Link + + \ No newline at end of file diff --git a/tests/practical/test_data/valid.html b/tests/practical/test_data/valid.html new file mode 100644 index 0000000..6eda44f --- /dev/null +++ b/tests/practical/test_data/valid.html @@ -0,0 +1,10 @@ + + + Test + + +

Hello, World!

+
+ Example Link + + \ No newline at end of file diff --git a/tests/practical/test_html_parser.py b/tests/practical/test_html_parser.py new file mode 100644 index 0000000..3cb7d66 --- /dev/null +++ b/tests/practical/test_html_parser.py @@ -0,0 +1,35 @@ +import pytest + +from src.practical.html_parser import HTMLValidator + + +def test_html_file_validator(): + assert HTMLValidator.validate_html("tests/practical/test_data/valid.html") is True + assert HTMLValidator.validate_html("tests/practical/test_data/invalid.html") is False + + +def test_invalid_file_path(): + with pytest.raises(FileNotFoundError): + assert HTMLValidator.validate_html("tests/practical/test_data/nonexistent.html") is False + + +def test_invalid_html(): + html = "

" + assert not HTMLValidator.validate_string(html) + + html = "

test" + assert not HTMLValidator.validate_string(html) + + html = "

test

" + assert not HTMLValidator.validate_string(html) + + +def test_valid_html(): + html = "" + assert HTMLValidator.validate_string(html) + + html = "

" + assert HTMLValidator.validate_string(html) + + html = "

test

" + assert HTMLValidator.validate_string(html)