Skip to content

Commit 6ac9d75

Browse files
authored
Ensure attribute exists before accessing it. (#12557)
Also adds tests to ensure this works, and doesn't blow up. Fixes https://read-the-docs.sentry.io/issues/4262263207
1 parent 2d0731c commit 6ac9d75

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

readthedocs/embed/tests/test_links.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,3 +149,19 @@ def test_two_links():
149149
firsturl.expected,
150150
secondurl.expected,
151151
)
152+
153+
154+
def test_missing_href_attribute():
155+
"""Test that links without href attribute don't cause errors."""
156+
pq = PyQuery('<body><a>Link without href</a></body>')
157+
response = clean_references(pq, html_base_url)
158+
# Should not raise KeyError, just skip the link
159+
assert response.find("a") is not None
160+
161+
162+
def test_missing_src_attribute():
163+
"""Test that images without src attribute don't cause errors."""
164+
pq = PyQuery('<body><img alt="image without src"></img></body>')
165+
response = clean_references(pq, html_base_url)
166+
# Should not raise KeyError, just skip the image
167+
assert response.find("img") is not None

readthedocs/embed/utils.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,11 @@ def clean_references(obj, url, html_raw_response=False):
3434
for tag in obj.find("a") + obj.find("img"):
3535
base_url = urlparse(url)
3636
attribute = "href" if tag.tag == "a" else "src"
37+
38+
# Skip if the attribute doesn't exist
39+
if attribute not in tag.attrib:
40+
continue
41+
3742
value = tag.attrib[attribute]
3843

3944
# We need to make all internal links/images, to be absolute

0 commit comments

Comments
 (0)