1"""``pyshacl.validator_conformance``: SHT and DASH expected-result checks.
2
3The SHT comparison unfolds both report descriptions into trees, so a blank
4node shared by several results (one shape's ``sh:path``) equals separate
5copies in the expected graph, as in pySHACL. It is stricter than pySHACL's
6focus/value/path keys: every retained field and multiplicity must match.
7"""
8
9import logging
10from collections import Counter
11
12from rdflib import BNode, Namespace, URIRef
13from rdflib.graph import Graph
14from rdflib.namespace import RDF, RDFS, SH
15from rdflib.term import Node
16
17from pyshacl_turbo._native import ValidationFailure
18from pyshacl_turbo.conformance import (
19 DASH,
20 check_dash_result,
21 evaluate_query_testcase,
22 extract_query_and_expected_result,
23)
24from pyshacl_turbo.errors import ReportableRuntimeError
25
26SHT = Namespace("http://www.w3.org/ns/shacl-test#")
27
28
29class ReportTree:
30 """A report description unfolded through blank nodes into a comparable value."""
31
32 def __init__(self, graph: Graph, *, messages: bool, details: bool) -> None:
33 self.graph = graph
34 self.messages = messages
35 self.details = details
36
37 def _kept(self, predicate: Node, value: Node) -> bool:
38 if predicate == RDF.type and value == RDFS.Resource:
39 return False
40 if predicate == SH.resultMessage:
41 return self.messages
42 return predicate != SH.detail or self.details
43
44 def unfold(self, node: Node, path: frozenset[Node] = frozenset()) -> object:
45 if not isinstance(node, BNode):
46 return node
47 if node in path:
48 raise ReportableRuntimeError("Cannot compare a cyclic blank-node report description")
49 inner = path | {node}
50 edges = Counter(
51 (predicate, self.unfold(value, inner))
52 for _, predicate, value in self.graph.triples((node, None, None))
53 if self._kept(predicate, value)
54 )
55 return frozenset(edges.items())
56
57
58def compare_sht_report(report: Graph, expected: Graph, expected_root: URIRef | BNode) -> bool:
59 """True when the report's unfolded description equals the expected result's."""
60 actual_root = report.value(None, RDF.type, SH.ValidationReport, any=False)
61 if actual_root is None or report.value(actual_root, SH.conforms) is None:
62 raise ReportableRuntimeError("The validation report must declare sh:conforms")
63 results = list(expected.objects(expected_root, SH.result))
64 messages = any(expected.value(node, SH.resultMessage) is not None for node in results)
65 details = any(expected.value(node, SH.detail) is not None for node in results)
66 actual = ReportTree(report, messages=messages, details=details).unfold(actual_root)
67 wanted = ReportTree(expected, messages=messages, details=details).unfold(expected_root)
68 return actual == wanted
69
70
71def check_sht_result(
72 report_graph: Graph | ValidationFailure,
73 sht_graph: Graph,
74 sht_result_node: URIRef | BNode,
75 log: logging.Logger | None = None,
76) -> bool:
77 """Check one W3C SHACL test-suite outcome, accepting an expected sht:Failure."""
78 log = log or logging.getLogger(__name__)
79 expected_failure = sht_result_node == SHT.Failure
80 if isinstance(report_graph, ValidationFailure):
81 if not expected_failure:
82 log.error("Validation failed, but the SHT entry does not expect a failure.")
83 return expected_failure
84 if expected_failure:
85 log.error("SHT expects a validation failure, but validation produced a report.")
86 return False
87 if SH.ValidationReport not in set(sht_graph.objects(sht_result_node, RDF.type)):
88 raise ReportableRuntimeError("SHT expected result must have type sh:ValidationReport")
89 return compare_sht_report(report_graph, sht_graph, sht_result_node)
90
91
92__all__ = [
93 "DASH",
94 "SHT",
95 "check_dash_result",
96 "check_sht_result",
97 "compare_sht_report",
98 "evaluate_query_testcase",
99 "extract_query_and_expected_result",
100]