Skip to content

Commit

Permalink
Add a function to parse an Item from its canonical URI
Browse files Browse the repository at this point in the history
SPARQL results seem to be in this form.
  • Loading branch information
dseomn committed Oct 25, 2023
1 parent 91a9a85 commit 932c6be
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
7 changes: 7 additions & 0 deletions rock_paper_sand/wikidata_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ def uri(self) -> str:
"""
return f"{_ITEM_PREFIX_CANONICAL_URI}{self.id}"

@classmethod
def from_uri(cls, value: str) -> Self:
"""Returns the item parsed from its canonical URI."""
return cls(
_parse_id(value, prefixes=(_ITEM_PREFIX_CANONICAL_URI,), letter="Q")
)


_i = Item.from_string
Q_GREGORIAN_CALENDAR = _i("https://www.wikidata.org/wiki/Q12138")
Expand Down
12 changes: 12 additions & 0 deletions rock_paper_sand/wikidata_value_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ def test_item_uri(self) -> None:
wikidata_value.Item("Q1").uri,
)

def test_item_from_uri_invalid(self) -> None:
with self.assertRaisesRegex(ValueError, "Wikidata IRI or ID"):
wikidata_value.Item.from_uri("Q1")

def test_item_from_uri_valid(self) -> None:
self.assertEqual(
"Q1",
wikidata_value.Item.from_uri(
"http://www.wikidata.org/entity/Q1"
).id,
)

def test_invalid_property_id(self) -> None:
with self.assertRaisesRegex(ValueError, "Wikidata IRI or ID"):
wikidata_value.Property("foo")
Expand Down

0 comments on commit 932c6be

Please sign in to comment.