Skip to content

Commit a9955b4

Browse files
committed
wip
1 parent 8e041ae commit a9955b4

File tree

5 files changed

+113
-21
lines changed

5 files changed

+113
-21
lines changed

test/test_sparql/test_result.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from dataclasses import dataclass
99
from io import BytesIO, StringIO
1010
from pathlib import Path
11+
from test.utils.result import ResultType
1112
from typing import (
1213
IO,
1314
BinaryIO,
@@ -111,11 +112,11 @@ def check_serialized(format: str, result: Result, data: str) -> None:
111112
assert result == parsed_result
112113

113114

114-
class ResultType(str, enum.Enum):
115-
CONSTRUCT = "CONSTRUCT"
116-
DESCRIBE = "DESCRIBE"
117-
SELECT = "SELECT"
118-
ASK = "ASK"
115+
# class ResultType(str, enum.Enum):
116+
# CONSTRUCT = "CONSTRUCT"
117+
# DESCRIBE = "DESCRIBE"
118+
# SELECT = "SELECT"
119+
# ASK = "ASK"
119120

120121

121122
class ResultFormatTrait(enum.Enum):

test/test_w3c_spec/test_sparql_w3c_new.py

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,13 @@
44
import logging
55
from contextlib import ExitStack
66
from dataclasses import dataclass, field
7-
from pathlib import Path
7+
from pathlib import Path, PurePath
88
from test.data import TEST_DATA_DIR
99
from test.utils import ensure_suffix
1010
from test.utils.iri import URIMapper, file_uri_to_path
1111
from test.utils.namespace import MF, QT, UT
1212
from test.utils.rdftest import Manifest, ManifestEntry, params_from_sources
13+
from test.utils.result import ResultType, ResultTypeTrait
1314
from typing import Dict, Optional, Set, Type, Union
1415
from urllib.parse import urljoin
1516

@@ -19,6 +20,9 @@
1920
from rdflib.namespace import RDFS
2021
from rdflib.plugins.sparql.algebra import translateQuery, translateUpdate
2122
from rdflib.plugins.sparql.parser import parseQuery, parseUpdate
23+
from rdflib.plugins.sparql.results.graph import GraphResultParser
24+
from rdflib.plugins.sparql.results.rdfresults import RDFResultParser
25+
from rdflib.query import Result
2226
from rdflib.term import BNode, IdentifiedNode, Identifier, Literal, Node, URIRef
2327
from rdflib.util import guess_format
2428

@@ -133,8 +137,7 @@ def from_graph(cls, graph: Graph, identifier: Identifier) -> "GraphData":
133137
raise ValueError(f"invalid identifier {identifier!r}")
134138

135139
def load_into(self, manifest: Manifest, dataset: Dataset) -> None:
136-
graph_local = manifest.uri_mapper.to_local(self.graph_id)
137-
graph_path = file_uri_to_path(graph_local, Path)
140+
graph_local, graph_path = manifest.uri_mapper.to_local(self.graph_id)
138141
graph_text = graph_path.read_text()
139142
public_id = self.label if self.label is not None else self.graph_id
140143
logging.debug(
@@ -237,14 +240,53 @@ def __post_init__(self) -> None:
237240
# def query(self) ->
238241

239242

243+
# class ResultType(enum.Enum):
244+
# SELECT = "SELECT"
245+
# ASK = "ASK"
246+
247+
248+
class ResultFileHelper:
249+
extentions = {
250+
"srx": "xml",
251+
"srj": "json",
252+
"csv": "csv",
253+
}
254+
255+
# @classmethod
256+
# def guess_format(cls, path: PurePath) -> Optional[str]:
257+
# return cls.extentions.get(path.suffix[1:], None)
258+
259+
@classmethod
260+
def load_result(cls, uri_mapper: URIMapper, result_uri: str, type: str) -> Result:
261+
result_local, result_path = uri_mapper.to_local(result_uri)
262+
ext = result_path.suffix[1:]
263+
format = cls.extentions.get(ext)
264+
if format is not None:
265+
with result_path.open("r") as tio:
266+
return Result.parse(tio, format=format)
267+
graph = Graph()
268+
graph.parse(result_path, publicID=result_uri)
269+
return RDFResultParser().parse(graph)
270+
271+
# if ResultTypeTrait.GRAPH_RESULT in ResultType.ASK.info.traits:
272+
# RDFResultParser
273+
274+
# format = cls.guess_format(path)
275+
# if type in ("ASK", "SELECT"):
276+
# with path.open("r") as tio:
277+
# return Result.parse(tio, format=format)
278+
# if type in ("DESCRIBE", "CONSTRUCT"):
279+
# with path.open("rb") as bio:
280+
# return GraphResultParser.parse(bio, format=format)
281+
282+
240283
BLANK_GRAPH = Graph()
241284

242285

243286
def check_syntax(entry: SPARQLEntry) -> None:
244287
assert entry.query is not None
245288
assert entry.type_info.query_type is not None
246-
query_local = entry.manifest.uri_mapper.to_local(entry.query)
247-
query_path = file_uri_to_path(query_local, Path)
289+
query_local, query_path = entry.manifest.uri_mapper.to_local(entry.query)
248290
query_text = query_path.read_text()
249291
logging.debug("query = %s\n%s", query_path, query_text)
250292
catcher: Optional[pytest.ExceptionInfo[Exception]] = None
@@ -270,14 +312,14 @@ def check_update(entry: SPARQLEntry) -> None:
270312
def check_query(entry: SPARQLEntry) -> None:
271313
assert entry.query is not None
272314
# assert entry.action_data is not None or entry.action_graph_data is not None
273-
query_local = entry.manifest.uri_mapper.to_local(entry.query)
274-
query_path = file_uri_to_path(query_local, Path)
315+
query_local, query_path = entry.manifest.uri_mapper.to_local(entry.query)
275316
query_text = query_path.read_text()
276317
logging.debug("query = %s\n%s", query_path, query_text)
277318
dataset = Dataset()
278319
if entry.action_data is not None:
279-
action_data_local = entry.manifest.uri_mapper.to_local(entry.action_data)
280-
action_data_path = file_uri_to_path(action_data_local, Path)
320+
action_data_local, action_data_path = entry.manifest.uri_mapper.to_local(
321+
entry.action_data
322+
)
281323
action_data_text = action_data_path.read_text()
282324
logging.debug("action_data = %s\n%s", action_data_path, action_data_text)
283325
dataset.default_context.parse(

test/utils/iri.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,13 @@
55

66
# import logging
77
from dataclasses import dataclass
8-
from pathlib import PurePath, PurePosixPath, PureWindowsPath
8+
from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath
99
from test.utils import ensure_suffix
1010
from typing import Callable, Optional, Set, Tuple, Type, TypeVar, Union
1111
from urllib.parse import quote, unquote, urlparse, urlsplit, urlunsplit
1212

1313
from nturl2path import url2pathname as nt_url2pathname
1414

15-
from rdflib.plugins.sparql.parser import Path
16-
1715
PurePathT = TypeVar("PurePathT", bound=PurePath)
1816

1917

@@ -92,21 +90,24 @@ def from_tuple(cls, value: URIMappingTupleType) -> "URIMapping":
9290
class URIMapper:
9391
mappings: Set[URIMapping]
9492

95-
def to_local(self, remote: str) -> Path:
93+
def to_local_uri(self, remote: str) -> Tuple[str, Path]:
9694
mapping: URIMapping
9795
for mapping in self.mappings:
9896
try:
99-
return rebase_url(remote, mapping.remote, mapping.local)
97+
file_uri = rebase_url(remote, mapping.remote, mapping.local)
98+
file_path = file_uri_to_path(file_uri, Path)
99+
return (file_uri, file_path)
100100
except ValueError:
101101
# logging.debug("failed to map using %s", mapping, exc_info=True)
102102
continue
103103
raise LookupError(f"could not map {remote} to local")
104104

105-
def to_remote(self, local: str) -> Path:
105+
def to_remote(self, local: Union[str, PurePath]) -> str:
106106
mapping: URIMapping
107+
local_uri = local.as_uri() if isinstance(local, PurePath) else local
107108
for mapping in self.mappings:
108109
try:
109-
return rebase_url(local, mapping.local, mapping.remote)
110+
return rebase_url(local_uri, mapping.local, mapping.remote)
110111
except ValueError:
111112
# logging.debug("failed to map using %s", mapping, exc_info=True)
112113
continue

test/utils/rdftest.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,8 @@ def from_sources(
149149
) -> Generator["Manifest", None, None]:
150150
for source in sources:
151151
source = GraphSource.from_source(source)
152+
logging.error("source.path = %s", source.path)
153+
logging.error("source.path.absolute() = %s", source.path.absolute())
152154
source_path_uri = source.path.absolute().as_uri()
153155
logging.debug("source_path_uri = %s", source_path_uri)
154156
local_base = urljoin(source_path_uri, ".")

test/utils/result.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import enum
2+
from dataclasses import dataclass
3+
from functools import lru_cache
4+
from typing import Dict, Set
5+
6+
ResultTypeInfoDict = Dict["ResultType", "ResultTypeInfo"]
7+
8+
9+
class ResultTypeTrait(enum.Enum):
10+
GRAPH_RESULT = enum.auto()
11+
12+
13+
class ResultType(str, enum.Enum):
14+
CONSTRUCT = "CONSTRUCT"
15+
DESCRIBE = "DESCRIBE"
16+
SELECT = "SELECT"
17+
ASK = "ASK"
18+
19+
@classmethod
20+
@lru_cache(maxsize=None)
21+
def info_dict(cls) -> "ResultTypeInfoDict":
22+
return ResultTypeInfo.make_dict(
23+
ResultTypeInfo(ResultType.CONSTRUCT, {ResultTypeTrait.GRAPH_RESULT}),
24+
ResultTypeInfo(ResultType.DESCRIBE, {ResultTypeTrait.GRAPH_RESULT}),
25+
ResultTypeInfo(ResultType.CONSTRUCT, set()),
26+
ResultTypeInfo(ResultType.CONSTRUCT, set()),
27+
)
28+
29+
@property
30+
def info(self) -> "ResultTypeInfo":
31+
return self.info_dict()[self]
32+
33+
@classmethod
34+
@lru_cache(maxsize=None)
35+
def set(cls) -> Set["ResultType"]:
36+
return set(*cls)
37+
38+
39+
@dataclass(frozen=True)
40+
class ResultTypeInfo:
41+
type: ResultType
42+
traits: Set[ResultTypeTrait]
43+
44+
@classmethod
45+
def make_dict(cls, *items: "ResultTypeInfo") -> ResultTypeInfoDict:
46+
return dict((info.type, info) for info in items)

0 commit comments

Comments
 (0)