Skip to content

Commit

Permalink
Add a function for SPARQL queries
Browse files Browse the repository at this point in the history
  • Loading branch information
dseomn committed Oct 23, 2023
1 parent df1bdfa commit f63a512
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions rock_paper_sand/wikidata.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,16 @@ def item(self, qid: str) -> Any:
self._item_by_qid[qid] = response.json()["entities"][qid]
return self._item_by_qid[qid]

def sparql(self, query: str) -> Any:
"""Returns results from a SPARQL query."""
response = self._session.get(
"https://query.wikidata.org/sparql",
params=[("query", query)],
headers={"Accept": "application/sparql-results+json"},
)
response.raise_for_status()
return response.json()["results"]["bindings"]


def _release_status(
item: Any,
Expand Down
21 changes: 21 additions & 0 deletions rock_paper_sand/wikidata_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,27 @@ def test_item(self) -> None:
self._mock_session.mock_calls,
)

def test_sparql(self) -> None:
self._mock_session.get.return_value.json.return_value = {
"results": {"bindings": [{"foo": "bar"}]}
}

results = self._api.sparql("SELECT ...")

self.assertEqual([{"foo": "bar"}], results)
self.assertSequenceEqual(
(
mock.call.get(
"https://query.wikidata.org/sparql",
params=[("query", "SELECT ...")],
headers={"Accept": "application/sparql-results+json"},
),
mock.call.get().raise_for_status(),
mock.call.get().json(),
),
self._mock_session.mock_calls,
)


class WikidataUtilsTest(parameterized.TestCase):
# pylint: disable=protected-access
Expand Down

0 comments on commit f63a512

Please sign in to comment.