1"""DASH expected-result adapters. SPARQL execution remains in the Rust engine."""
2
3from io import StringIO
4
5from rdflib import BNode, Literal, Namespace
6from rdflib.compare import isomorphic
7from rdflib.graph import Graph
8from rdflib.namespace import OWL, RDF, RDFS, SH
9from rdflib.query import Result
10
11from . import _native
12from .rdf import input_graph, union
13
14DASH = Namespace("http://datashapes.org/dash#")
15
16
17def query_prefixes(graph, node):
18 prefixes = dict(graph.namespaces())
19 pending, seen = list(graph.objects(node, SH.prefixes)), set()
20 if pending:
21 pending.extend(graph.subjects(RDF.type, OWL.Ontology))
22 pending.append(graph.identifier)
23 while pending:
24 resource = pending.pop()
25 if resource in seen:
26 continue
27 seen.add(resource)
28 pending.extend(graph.objects(resource, OWL.imports))
29 for declaration in graph.objects(resource, SH.declare):
30 prefix = graph.value(declaration, SH.prefix, any=False)
31 namespace = graph.value(declaration, SH.namespace, any=False)
32 if prefix is None or namespace is None:
33 raise ValueError("Incomplete sh:declare")
34 prefixes[str(prefix)] = namespace
35 return "".join(f"PREFIX {p}: <{ns}>\n" for p, ns in sorted(prefixes.items()))
36
37
38def extract_query_and_expected_result(test_case, graph, log=None):
39 text = graph.value(test_case, SH.select, any=False)
40 expected = graph.value(test_case, DASH.expectedResult, any=False)
41 if text is None or expected is None:
42 raise RuntimeError("QueryTestCase requires sh:select and dash:expectedResult")
43 result = Result.parse(StringIO(str(expected)), format="json")
44 if result.type != "SELECT":
45 raise RuntimeError("QueryTestCase expected result must be SELECT")
46 return query_prefixes(graph, test_case) + str(text), result
47
48
49def evaluate_query_testcase(query_graph, test_case, log=None):
50 query, expected = extract_query_and_expected_result(test_case, query_graph, log)
51 snapshot = input_graph(query_graph)
52 actual = Result.parse(
53 StringIO(_native.query(snapshot.source, snapshot.format, query)), format="json"
54 )
55 if actual.type != "SELECT":
56 raise RuntimeError("QueryTestCase query must return SELECT results")
57 matches = set(actual.vars) == set(expected.vars) and [row.asdict() for row in actual] == [
58 row.asdict() for row in expected
59 ]
60 return matches, None if matches else "SPARQL SELECT result differs from dash:expectedResult"
61
62
63def report_subgraph(graph, root, messages, details):
64 result, seen, pending = Graph(), set(), [root]
65 while pending:
66 node = pending.pop()
67 if node in seen:
68 continue
69 seen.add(node)
70 for _, predicate, value in graph.triples((node, None, None)):
71 if (
72 (predicate == RDF.type and value == RDFS.Resource)
73 or (predicate == SH.resultMessage and not messages)
74 or (predicate == SH.detail and not details)
75 ):
76 continue
77 result.add((node, predicate, value))
78 if isinstance(value, BNode):
79 pending.append(value)
80 return result
81
82
83def compare_reports(actual, expected, expected_root):
84 actual_root = actual.value(None, RDF.type, SH.ValidationReport, any=False)
85 if (
86 actual_root is None
87 or actual.value(actual_root, SH.conforms) is None
88 or expected.value(expected_root, SH.conforms) is None
89 ):
90 raise RuntimeError("Expected and actual reports must declare sh:conforms")
91 expected_results = list(expected.objects(expected_root, SH.result))
92 messages = any(expected.value(node, SH.resultMessage) is not None for node in expected_results)
93 details = any(expected.value(node, SH.detail) is not None for node in expected_results)
94 return isomorphic(
95 report_subgraph(actual, actual_root, messages, details),
96 report_subgraph(expected, expected_root, messages, details),
97 )
98
99
100def _literal_matches(expected, actual):
101 if not isinstance(actual, Literal):
102 return False
103 try:
104 return bool(expected.eq(actual))
105 except (TypeError, NotImplementedError):
106 # Incomparable literal values are an expected-result mismatch.
107 return False
108
109
110def check_dash_result(report, expected_graph, expanded_data):
111 expected = union(expected_graph)
112 data = None
113 checks = []
114 for case in expected.subjects(RDF.type, DASH.GraphValidationTestCase):
115 root = expected.value(case, DASH.expectedResult, any=False)
116 if root is None:
117 raise RuntimeError("GraphValidationTestCase requires dash:expectedResult")
118 checks.append(compare_reports(report, expected, root))
119 for case in expected.subjects(RDF.type, DASH.InferencingTestCase):
120 if data is None:
121 from .rdf import load_from_source
122
123 data = union(load_from_source(expanded_data))
124 results = list(expected.objects(case, DASH.expectedResult))
125 if not results:
126 raise RuntimeError("InferencingTestCase requires dash:expectedResult")
127 for result in results:
128 triple = tuple(
129 expected.value(result, p, any=False)
130 for p in (RDF.subject, RDF.predicate, RDF.object)
131 )
132 if None in triple:
133 raise RuntimeError("InferencingTestCase requires complete reified triples")
134 subject, predicate, value = triple
135 if isinstance(value, Literal):
136 checks.append(
137 any(
138 _literal_matches(value, actual)
139 for actual in data.objects(subject, predicate)
140 )
141 )
142 else:
143 checks.append(triple in data)
144 for case in expected.subjects(RDF.type, DASH.QueryTestCase):
145 try:
146 matches, _ = evaluate_query_testcase(expected, case)
147 except (ValueError, RuntimeError, KeyError, TypeError):
148 # DASH query cases intentionally test malformed queries/results.
149 # This is the expected-result checker, never a validator fallback.
150 matches = False
151 checks.append(matches)
152 for case in expected.subjects(RDF.type, DASH.FunctionTestCase):
153 expression = expected.value(case, DASH.expression, any=False)
154 result = expected.value(case, DASH.expectedResult, any=False)
155 if expression is None or result is None:
156 raise RuntimeError("FunctionTestCase requires dash:expression and dash:expectedResult")
157 query = query_prefixes(expected, case) + f"SELECT ({expression} AS ?result) WHERE {{}}"
158 snapshot = input_graph(expected)
159 actual = Result.parse(
160 StringIO(_native.query(snapshot.source, snapshot.format, query)), format="json"
161 )
162 checks.append([row.asdict().get("result") for row in actual] == [result])
163 if not checks:
164 raise RuntimeError("Expected graph contains no DASH test cases")
165 return all(checks)