Skip to content

Commit 089ce50

Browse files
committed
Explicitly ensure we catch calling .anchor on a nonexistent resource.
This already raised the right kind of exception, but sort of accidentally.
1 parent de0d258 commit 089ce50

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

referencing/_core.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -374,21 +374,20 @@ def anchor(self, uri: URI, name: str):
374374
if value is not None:
375375
return Retrieved(value=value, registry=registry)
376376

377-
resource = self.get(uri)
378-
if resource is not None:
379-
canonical_uri = resource.id()
380-
if canonical_uri is not None:
381-
value = registry._anchors.get((canonical_uri, name))
382-
if value is not None:
383-
return Retrieved(value=value, registry=registry)
377+
resource = self[uri]
378+
canonical_uri = resource.id()
379+
if canonical_uri is not None:
380+
value = registry._anchors.get((canonical_uri, name))
381+
if value is not None:
382+
return Retrieved(value=value, registry=registry)
384383

385384
if "/" in name:
386385
raise exceptions.InvalidAnchor(
387386
ref=uri,
388-
resource=self[uri],
387+
resource=resource,
389388
anchor=name,
390389
)
391-
raise exceptions.NoSuchAnchor(ref=uri, resource=self[uri], anchor=name)
390+
raise exceptions.NoSuchAnchor(ref=uri, resource=resource, anchor=name)
392391

393392
def contents(self, uri: URI) -> D:
394393
"""

referencing/tests/test_core.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,12 @@ def test_crawled_anchor(self):
181181
)
182182
assert retrieved.registry == registry.crawl()
183183

184+
def test_anchor_in_nonexistent_resource(self):
185+
registry = Registry()
186+
with pytest.raises(exceptions.NoSuchResource) as e:
187+
registry.anchor("urn:example", "foo")
188+
assert e.value == exceptions.NoSuchResource(ref="urn:example")
189+
184190
def test_init(self):
185191
one = Resource.opaque(contents={})
186192
two = ID_AND_CHILDREN.create_resource({"foo": "bar"})

0 commit comments

Comments
 (0)