Skip to content

Mocking SPARQLWrapper #242

@lu-pl

Description

@lu-pl

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions