Skip to content

Commit

Permalink
Add function to parse string snaks
Browse files Browse the repository at this point in the history
  • Loading branch information
dseomn committed Nov 10, 2023
1 parent 5ce0c7c commit d9186ae
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
11 changes: 11 additions & 0 deletions rock_paper_sand/wikidata_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,17 @@ def parse_snak_item(snak: Snak) -> ItemRef:
return ItemRef(snak["datavalue"]["value"]["id"])


def parse_snak_string(snak: Snak) -> str:
"""Returns a string value from a snak."""
if snak["snaktype"] != "value":
raise NotImplementedError(
f"Cannot parse non-value snak as a string: {snak}"
)
if snak["datatype"] != "string" or snak["datavalue"]["type"] != "string":
raise ValueError(f"Cannot parse non-string snak as a string: {snak}")
return snak["datavalue"]["value"]


def parse_snak_time(snak: Snak) -> tuple[datetime.datetime, datetime.datetime]:
"""Returns (earliest possible time, latest possible time) of a time snak."""
# https://doc.wikimedia.org/Wikibase/master/php/docs_topics_json.html#json_datavalues_time
Expand Down
48 changes: 48 additions & 0 deletions rock_paper_sand/wikidata_value_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,54 @@ def test_parse_snak_item(self) -> None:
),
)

@parameterized.named_parameters(
dict(
testcase_name="not_value",
snak={"snaktype": "somevalue"},
error_class=NotImplementedError,
error_regex=r"non-value",
),
dict(
testcase_name="datatype_not_string",
snak={"snaktype": "value", "datatype": "wikibase-item"},
error_class=ValueError,
error_regex=r"non-string",
),
dict(
testcase_name="type_not_string",
snak={
"snaktype": "value",
"datatype": "string",
"datavalue": {"type": "wikibase-entityid"},
},
error_class=ValueError,
error_regex=r"non-string",
),
)
def test_parse_snak_string_error(
self,
*,
snak: Any,
error_class: type[Exception],
error_regex: str,
) -> None:
with self.assertRaisesRegex(error_class, error_regex):
wikidata_value.parse_snak_string(wikidata_value.Snak(snak))

def test_parse_snak_string(self) -> None:
self.assertEqual(
"foo",
wikidata_value.parse_snak_string(
wikidata_value.Snak(
{
"snaktype": "value",
"datatype": "string",
"datavalue": {"type": "string", "value": "foo"},
}
)
),
)

@parameterized.named_parameters(
dict(
testcase_name="not_value",
Expand Down

0 comments on commit d9186ae

Please sign in to comment.