Skip to content

Commit

Permalink
Merge pull request #2345 from hypothesis/defensive-feed-construction
Browse files Browse the repository at this point in the history
Be slightly more defensive when processing annotations for the atom feed.
  • Loading branch information
tilgovi committed Jul 3, 2015
2 parents b3d7b3e + 7050db2 commit 3ccc68e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
26 changes: 21 additions & 5 deletions h/atom_feed.py
Expand Up @@ -82,8 +82,18 @@ def _feed_entry_from_annotation(
}

def get_selection(annotation):
for target in annotation.get("target", []):
for selector in target["selector"]:
targets = annotation.get("target")
if not isinstance(targets, list):
return
for target in targets:
if not isinstance(target, dict):
continue
selectors = target.get("selector")
if not isinstance(selectors, list):
continue
for selector in selectors:
if not isinstance(selector, dict):
continue
if "exact" in selector:
return selector["exact"]

Expand Down Expand Up @@ -111,9 +121,15 @@ def get_selection(annotation):
entry["links"].append({"rel": "alternate", "type": "application/json",
"href": annotation_api_url(annotation)})

for target in annotation.get('target', []):
entry["links"].append({"rel": "related",
"href": target.get('source')})
targets = annotation.get("target")
if isinstance(targets, list):
for target in targets:
if not isinstance(target, dict):
continue
source = target.get("source")
if source is None:
continue
entry["links"].append({"rel": "related", "href": source})

return entry

Expand Down
19 changes: 19 additions & 0 deletions h/test/atom_feed_test.py
Expand Up @@ -356,3 +356,22 @@ def test_annotation_with_targets():
assert feed["entries"][0]["links"][1]["href"] == target1["source"]
assert feed["entries"][0]["links"][2]["rel"] == "related"
assert feed["entries"][0]["links"][2]["href"] == target2["source"]


def test_malformed_target():
# This annotation has a broken target (a dict instead of a list), but we
# shouldn't explode in this case.
annotation = factories.Annotation()
annotation['target'] = {
'selector': [
{'start': None, 'end': None, 'type': 'TextPositionSelector'},
{'exact': None, 'prefix': None, 'type': 'TextQuoteSelector', 'suffix': None}
]
}

feed = atom_feed._feed_from_annotations(
[annotation],
atom_url=None,
annotation_url=_mock_annotation_url_function())

assert len(feed["entries"]) == 1

0 comments on commit 3ccc68e

Please sign in to comment.