Skip to content

Commit fd5044c

Browse files
authored
HTML/XML tag checker (#195)
1 parent 53664be commit fd5044c

4 files changed

Lines changed: 119 additions & 0 deletions

File tree

‎src/practical/html_parser.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from html.parser import HTMLParser
2+
3+
4+
class HTMLValidator:
5+
"""Check whether HTML content is well-formed, i.e. every tag has a matching close tag.
6+
7+
This only verifies tag balance/nesting via a streaming `html.parser.HTMLParser`, not
8+
conformance to the actual HTML5 element vocabulary or content model — unknown tag names
9+
(e.g. `<foobar>`) are accepted as well-formed as long as they're properly closed.
10+
"""
11+
12+
@staticmethod
13+
def validate_html(path: str) -> bool:
14+
"""Return True if the file at `path` is well-formed HTML, False otherwise.
15+
16+
Reads and parses the file in chunks so memory use stays bounded regardless of file size.
17+
"""
18+
parser = TagChecker()
19+
20+
try:
21+
with open(path, "r", encoding="utf-8") as f:
22+
while chunk := f.read(64000):
23+
parser.feed(chunk)
24+
parser.close()
25+
except FileNotFoundError as e:
26+
raise e
27+
except ValueError:
28+
return False
29+
30+
return parser.tag_stack == []
31+
32+
@staticmethod
33+
def validate_string(string: str) -> bool:
34+
"""Return True if `string` is well-formed HTML, False otherwise."""
35+
parser = TagChecker()
36+
37+
try:
38+
parser.feed(string)
39+
parser.close()
40+
except ValueError:
41+
return False
42+
return parser.tag_stack == []
43+
44+
45+
class TagChecker(HTMLParser):
46+
"""Tracks open tags on a stack, raising ValueError on any mismatched or unclosed tag."""
47+
48+
def __init__(self):
49+
super().__init__()
50+
self.tag_stack = []
51+
52+
def handle_starttag(self, tag, attrs):
53+
self.tag_stack.append(tag)
54+
55+
def handle_endtag(self, tag):
56+
if not self.tag_stack or self.tag_stack[-1] != tag:
57+
raise ValueError(f"Mismatched end tag: {tag}")
58+
self.tag_stack.pop()
59+
60+
def close(self):
61+
"""Flush any buffered data, then raise ValueError if any tags were left unclosed."""
62+
super().close()
63+
if self.tag_stack:
64+
raise ValueError(f"Unclosed tags: {self.tag_stack}")
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<html>
2+
<head>
3+
<title>Test</title>
4+
<head>
5+
<body>
6+
<h1>Hello, World!
7+
<br/>
8+
<a href="https://www.example.com">Example Link</a>
9+
</body>
10+
</html>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<html>
2+
<head>
3+
<title>Test</title>
4+
</head>
5+
<body>
6+
<h1>Hello, World!</h1>
7+
<br/>
8+
<a href="https://www.example.com">Example Link</a>
9+
</body>
10+
</html>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import pytest
2+
3+
from src.practical.html_parser import HTMLValidator
4+
5+
6+
def test_html_file_validator():
7+
assert HTMLValidator.validate_html("tests/practical/test_data/valid.html") is True
8+
assert HTMLValidator.validate_html("tests/practical/test_data/invalid.html") is False
9+
10+
11+
def test_invalid_file_path():
12+
with pytest.raises(FileNotFoundError):
13+
assert HTMLValidator.validate_html("tests/practical/test_data/nonexistent.html") is False
14+
15+
16+
def test_invalid_html():
17+
html = "<p>"
18+
assert not HTMLValidator.validate_string(html)
19+
20+
html = "<p>test"
21+
assert not HTMLValidator.validate_string(html)
22+
23+
html = "<h1><p>test</p></h1><p>"
24+
assert not HTMLValidator.validate_string(html)
25+
26+
27+
def test_valid_html():
28+
html = ""
29+
assert HTMLValidator.validate_string(html)
30+
31+
html = "<p></p>"
32+
assert HTMLValidator.validate_string(html)
33+
34+
html = "<p>test</p><test></test>"
35+
assert HTMLValidator.validate_string(html)

0 commit comments

Comments
 (0)