Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocking SPARQLWrapper #242

Open
lu-pl opened this issue Dec 6, 2024 · 0 comments
Open

Mocking SPARQLWrapper #242

lu-pl opened this issue Dec 6, 2024 · 0 comments

Comments

@lu-pl
Copy link

lu-pl commented Dec 6, 2024

The question, how to (best) mock SPARQLWrapper objects probably comes up for most projects using SPARQLWrapper at some point. So having a generic mocking facility as part of the SPARQLWrapper library would be a real asset.

Unfortunately, since SPARQLWrapper does not use requests, mocking SPARQLWrapper is not entirely straight forward.

Here is a quick draft of a solution I came up with:

from contextlib import contextmanager
from functools import partial
from http.client import HTTPResponse
from unittest.mock import MagicMock, patch

from SPARQLWrapper import SPARQLWrapper
from SPARQLWrapper.Wrapper import QueryResult
from rdflib import Graph
from rdflib.plugins.sparql.processor import SPARQLResult

class SPARQLWrapperLocalMock(SPARQLWrapper):
    def __init__(self, *args, graph, **kwargs):
        self.graph = graph
        super().__init__(*args, **kwargs)

    def query(self):
        mock_response: MagicMock = MagicMock(spec=HTTPResponse)

        result: SPARQLResult = self.graph.query(self.queryString)
        mock_response.read.return_value = result.serialize(format=self.returnFormat)

        return QueryResult(mock_response)

@contextmanager
def SPARQLWrapperLocalTarget(graph: Graph):
    with patch("__main__.SPARQLWrapper", partial(SPARQLWrapperLocalMock, graph=graph)):
        yield graph

The main idea of this is to have the SPARQLWrapper.query method target a local rdflib.Graph instance instead of an actual remote triplestore and apply the respective SPARQLWrapper patch within a context manager.

A simple usage example would be:

from SPARQLWrapper import SPARQLWrapper
from rdflib import Graph
from sparqlwrapper_mock_draft.latest import SPARQLWrapperLocalTarget

data = """
BASE <http://example.org/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX rel: <http://www.perceive.net/schemas/relationship/>

<#green-goblin>
  rel:enemyOf <#spiderman> ;
  a foaf:Person ;    # in the context of the Marvel universe
  foaf:name "Green Goblin" .

<#spiderman>
  rel:enemyOf <#green-goblin> ;
  a foaf:Person ;
  foaf:name "Spiderman" .
"""

graph = Graph().parse(data=data, format="ttl")

def code_unter_test():
    s = SPARQLWrapper("some.endpoint")
    s.setReturnFormat("json")
    s.setQuery("select ?s ?p ?o where {?s ?p ?o .}")

    print(s.queryAndConvert())

with SPARQLWrapperLocalTarget(graph):
    code_unter_test()

This is not at all tested and probably needs some polishing, but might be a good starting point for a discussion about mocking SPARQLWrapper.

One very basic question would be: Should a mocking facility even be part of SPARQLWrapper or is mocking considered more of an external responsibility?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant