1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
|
from collections import Counter
from typing import Set, Tuple
from unittest.case import expectedFailure
import pytest
from rdflib.term import Node
from rdflib import Graph, RDF, BNode, URIRef, Namespace, ConjunctiveGraph, Literal
from rdflib.namespace import FOAF
from rdflib.compare import to_isomorphic, to_canonical_graph
import rdflib
from rdflib.plugins.stores.memory import Memory
from io import StringIO
import unittest
from .testutils import GraphHelper
def get_digest_value(rdf, mimetype):
graph = Graph()
graph.load(StringIO(rdf), format=mimetype)
stats = {}
ig = to_isomorphic(graph)
result = ig.graph_digest(stats)
print(stats)
return result
def negative_graph_match_test():
"""Test of FRIR identifiers against tricky RDF graphs with blank nodes."""
testInputs = [
[
str(
"""@prefix : <http://example.org/ns#> .
<http://example.org> :rel
[ :label "Same" ].
"""
),
str(
"""@prefix : <http://example.org/ns#> .
<http://example.org> :rel
[ :label "Same" ],
[ :label "Same" ].
"""
),
False,
],
[
str(
"""@prefix : <http://example.org/ns#> .
<http://example.org> :rel
<http://example.org/a>.
"""
),
str(
"""@prefix : <http://example.org/ns#> .
<http://example.org> :rel
<http://example.org/a>,
<http://example.org/a>.
"""
),
True,
],
[
str(
"""@prefix : <http://example.org/ns#> .
:linear_two_step_symmetry_start :related [ :related [ :related :linear_two_step_symmatry_end]],
[ :related [ :related :linear_two_step_symmatry_end]]."""
),
str(
"""@prefix : <http://example.org/ns#> .
:linear_two_step_symmetry_start :related [ :related [ :related :linear_two_step_symmatry_end]],
[ :related [ :related :linear_two_step_symmatry_end]]."""
),
True,
],
[
str(
"""@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
:rel [
:rel _:a;
];
];
];
]."""
),
str(
"""@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
:rel [
:rel [
:rel _:a;
];
];
];
];
]."""
),
False,
],
# This test fails because the algorithm purposefully breaks the symmetry of symetric
[
str(
"""@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
:rel [
:rel _:a;
];
];
];
]."""
),
str(
"""@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
:rel [
:rel _:a;
];
];
];
]."""
),
True,
],
[
str(
"""@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:label "foo";
:rel [
:rel [
:rel _:a;
];
];
];
]."""
),
str(
"""@prefix : <http://example.org/ns#> .
_:a :rel [
:rel [
:rel [
:rel [
:rel _:a;
];
];
];
]."""
),
False,
],
[
str(
"""@prefix : <http://example.org/ns#> .
_:0001 :rel _:0003, _:0004.
_:0002 :rel _:0005, _:0006.
_:0003 :rel _:0001, _:0007, _:0010.
_:0004 :rel _:0001, _:0009, _:0008.
_:0005 :rel _:0002, _:0007, _:0009.
_:0006 :rel _:0002, _:0008, _:0010.
_:0007 :rel _:0003, _:0005, _:0009.
_:0008 :rel _:0004, _:0006, _:0010.
_:0009 :rel _:0004, _:0005, _:0007.
_:0010 :rel _:0003, _:0006, _:0008.
"""
),
str(
"""@prefix : <http://example.org/ns#> .
_:0001 :rel _:0003, _:0004.
_:0002 :rel _:0005, _:0006.
_:0003 :rel _:0001, _:0007, _:0010.
_:0008 :rel _:0004, _:0006, _:0010.
_:0009 :rel _:0004, _:0005, _:0007.
_:0010 :rel _:0003, _:0006, _:0008.
_:0004 :rel _:0001, _:0009, _:0008.
_:0005 :rel _:0002, _:0007, _:0009.
_:0006 :rel _:0002, _:0008, _:0010.
_:0007 :rel _:0003, _:0005, _:0009.
"""
),
True,
],
]
def fn(rdf1, rdf2, identical):
digest1 = get_digest_value(rdf1, "text/turtle")
digest2 = get_digest_value(rdf2, "text/turtle")
print(rdf1)
print(digest1)
print(rdf2)
print(digest2)
assert (digest1 == digest2) == identical
for inputs in testInputs:
yield fn, inputs[0], inputs[1], inputs[2]
@pytest.mark.parametrize("fn, rdf1, rdf2, identical", negative_graph_match_test())
def test_negative_graph_match(fn, rdf1, rdf2, identical):
fn(rdf1, rdf2, identical)
def test_issue494_collapsing_bnodes():
"""Test for https://github.com/RDFLib/rdflib/issues/494 collapsing BNodes"""
g = Graph()
g += [
(BNode("Na1a8fbcf755f41c1b5728f326be50994"), RDF["object"], URIRef("source")),
(BNode("Na1a8fbcf755f41c1b5728f326be50994"), RDF["predicate"], BNode("vcb3")),
(BNode("Na1a8fbcf755f41c1b5728f326be50994"), RDF["subject"], BNode("vcb2")),
(BNode("Na1a8fbcf755f41c1b5728f326be50994"), RDF["type"], RDF["Statement"]),
(BNode("Na713b02f320d409c806ff0190db324f4"), RDF["object"], URIRef("target")),
(BNode("Na713b02f320d409c806ff0190db324f4"), RDF["predicate"], BNode("vcb0")),
(BNode("Na713b02f320d409c806ff0190db324f4"), RDF["subject"], URIRef("source")),
(BNode("Na713b02f320d409c806ff0190db324f4"), RDF["type"], RDF["Statement"]),
(BNode("Ndb804ba690a64b3dbb9063c68d5e3550"), RDF["object"], BNode("vr0KcS4")),
(
BNode("Ndb804ba690a64b3dbb9063c68d5e3550"),
RDF["predicate"],
BNode("vrby3JV"),
),
(BNode("Ndb804ba690a64b3dbb9063c68d5e3550"), RDF["subject"], URIRef("source")),
(BNode("Ndb804ba690a64b3dbb9063c68d5e3550"), RDF["type"], RDF["Statement"]),
(BNode("Ndfc47fb1cd2d4382bcb8d5eb7835a636"), RDF["object"], URIRef("source")),
(BNode("Ndfc47fb1cd2d4382bcb8d5eb7835a636"), RDF["predicate"], BNode("vcb5")),
(BNode("Ndfc47fb1cd2d4382bcb8d5eb7835a636"), RDF["subject"], URIRef("target")),
(BNode("Ndfc47fb1cd2d4382bcb8d5eb7835a636"), RDF["type"], RDF["Statement"]),
(BNode("Nec6864ef180843838aa9805bac835c98"), RDF["object"], URIRef("source")),
(BNode("Nec6864ef180843838aa9805bac835c98"), RDF["predicate"], BNode("vcb4")),
(BNode("Nec6864ef180843838aa9805bac835c98"), RDF["subject"], URIRef("source")),
(BNode("Nec6864ef180843838aa9805bac835c98"), RDF["type"], RDF["Statement"]),
]
# print('graph length: %d, nodes: %d' % (len(g), len(g.all_nodes())))
# print('triple_bnode degrees:')
# for triple_bnode in g.subjects(RDF['type'], RDF['Statement']):
# print(len(list(g.triples([triple_bnode, None, None]))))
# print('all node degrees:')
g_node_degs = sorted(
[len(list(g.triples([node, None, None]))) for node in g.all_nodes()],
reverse=True,
)
# print(g_node_degs)
cg = to_canonical_graph(g)
# print('graph length: %d, nodes: %d' % (len(cg), len(cg.all_nodes())))
# print('triple_bnode degrees:')
# for triple_bnode in cg.subjects(RDF['type'], RDF['Statement']):
# print(len(list(cg.triples([triple_bnode, None, None]))))
# print('all node degrees:')
cg_node_degs = sorted(
[len(list(cg.triples([node, None, None]))) for node in cg.all_nodes()],
reverse=True,
)
# print(cg_node_degs)
assert len(g) == len(cg), "canonicalization changed number of triples in graph"
assert len(g.all_nodes()) == len(
cg.all_nodes()
), "canonicalization changed number of nodes in graph"
assert len(list(g.subjects(RDF["type"], RDF["Statement"]))) == len(
list(cg.subjects(RDF["type"], RDF["Statement"]))
), "canonicalization changed number of statements"
assert g_node_degs == cg_node_degs, "canonicalization changed node degrees"
# counter for subject, predicate and object nodes
g_pos_counts = Counter(), Counter(), Counter()
for t in g:
for i, node in enumerate(t):
g_pos_counts[i][t] += 1
g_count_signature = [sorted(c.values()) for c in g_pos_counts]
cg = to_canonical_graph(g)
cg_pos_counts = Counter(), Counter(), Counter()
for t in cg:
for i, node in enumerate(t):
cg_pos_counts[i][t] += 1
cg_count_signature = [sorted(c.values()) for c in cg_pos_counts]
assert (
g_count_signature == cg_count_signature
), "canonicalization changed node position counts"
def test_issue682_signing_named_graphs():
ns = Namespace("http://love.com#")
mary = BNode()
john = URIRef("http://love.com/lovers/john#")
cmary = URIRef("http://love.com/lovers/mary#")
cjohn = URIRef("http://love.com/lovers/john#")
store = Memory()
g = ConjunctiveGraph(store=store)
g.bind("love", ns)
gmary = Graph(store=store, identifier=cmary)
gmary.add((mary, ns["hasName"], Literal("Mary")))
gmary.add((mary, ns["loves"], john))
gjohn = Graph(store=store, identifier=cjohn)
gjohn.add((john, ns["hasName"], Literal("John")))
ig = to_isomorphic(g)
igmary = to_isomorphic(gmary)
assert len(igmary) == len(gmary)
assert len(ig) == len(g)
assert len(igmary) < len(ig)
assert ig.graph_digest() != igmary.graph_digest()
def test_issue725_collapsing_bnodes_2():
g = Graph()
g += [
(
BNode("N0a76d42406b84fe4b8029d0a7fa04244"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#object"),
BNode("v2"),
),
(
BNode("N0a76d42406b84fe4b8029d0a7fa04244"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"),
BNode("v0"),
),
(
BNode("N0a76d42406b84fe4b8029d0a7fa04244"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject"),
URIRef("urn:gp_learner:fixed_var:target"),
),
(
BNode("N0a76d42406b84fe4b8029d0a7fa04244"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"),
),
(
BNode("N2f62af5936b94a8eb4b1e4bfa8e11d95"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#object"),
BNode("v1"),
),
(
BNode("N2f62af5936b94a8eb4b1e4bfa8e11d95"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"),
BNode("v0"),
),
(
BNode("N2f62af5936b94a8eb4b1e4bfa8e11d95"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject"),
URIRef("urn:gp_learner:fixed_var:target"),
),
(
BNode("N2f62af5936b94a8eb4b1e4bfa8e11d95"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"),
),
(
BNode("N5ae541f93e1d4e5880450b1bdceb6404"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#object"),
BNode("v5"),
),
(
BNode("N5ae541f93e1d4e5880450b1bdceb6404"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"),
BNode("v4"),
),
(
BNode("N5ae541f93e1d4e5880450b1bdceb6404"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject"),
URIRef("urn:gp_learner:fixed_var:target"),
),
(
BNode("N5ae541f93e1d4e5880450b1bdceb6404"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"),
),
(
BNode("N86ac7ca781f546ae939b8963895f672e"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#object"),
URIRef("urn:gp_learner:fixed_var:source"),
),
(
BNode("N86ac7ca781f546ae939b8963895f672e"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"),
BNode("v0"),
),
(
BNode("N86ac7ca781f546ae939b8963895f672e"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject"),
URIRef("urn:gp_learner:fixed_var:target"),
),
(
BNode("N86ac7ca781f546ae939b8963895f672e"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"),
),
(
BNode("Nac82b883ca3849b5ab6820b7ac15e490"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#object"),
BNode("v1"),
),
(
BNode("Nac82b883ca3849b5ab6820b7ac15e490"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate"),
BNode("v3"),
),
(
BNode("Nac82b883ca3849b5ab6820b7ac15e490"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#subject"),
URIRef("urn:gp_learner:fixed_var:target"),
),
(
BNode("Nac82b883ca3849b5ab6820b7ac15e490"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#Statement"),
),
]
turtle = """
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
[] a rdf:Statement ;
rdf:object [ ] ;
rdf:predicate _:v0 ;
rdf:subject <urn:gp_learner:fixed_var:target> .
[] a rdf:Statement ;
rdf:object _:v1 ;
rdf:predicate _:v0 ;
rdf:subject <urn:gp_learner:fixed_var:target> .
[] a rdf:Statement ;
rdf:object [ ] ;
rdf:predicate [ ] ;
rdf:subject <urn:gp_learner:fixed_var:target> .
[] a rdf:Statement ;
rdf:object <urn:gp_learner:fixed_var:source> ;
rdf:predicate _:v0 ;
rdf:subject <urn:gp_learner:fixed_var:target> .
[] a rdf:Statement ;
rdf:object _:v1 ;
rdf:predicate [ ] ;
rdf:subject <urn:gp_learner:fixed_var:target> ."""
# g = Graph()
# g.parse(data=turtle, format='turtle')
stats = {}
cg = rdflib.compare.to_canonical_graph(g, stats=stats)
# print ('graph g length: %d, nodes: %d' % (len(g), len(g.all_nodes())))
# print ('triple_bnode degrees:')
# for triple_bnode in g.subjects(rdflib.RDF['type'], rdflib.RDF['Statement']):
# print (len(list(g.triples([triple_bnode, None, None]))))
# print ('all node out-degrees:')
# print (sorted(
# [len(list(g.triples([node, None, None]))) for node in g.all_nodes()]))
# print ('all node in-degrees:')
# print (sorted(
# [len(list(g.triples([None, None, node]))) for node in g.all_nodes()]))
# print(g.serialize(format='n3'))
#
# print ('graph cg length: %d, nodes: %d' % (len(cg), len(cg.all_nodes())))
# print ('triple_bnode degrees:')
# for triple_bnode in cg.subjects(rdflib.RDF['type'],
# rdflib.RDF['Statement']):
# print (len(list(cg.triples([triple_bnode, None, None]))))
# print ('all node out-degrees:')
# print (sorted(
# [len(list(cg.triples([node, None, None]))) for node in cg.all_nodes()]))
# print ('all node in-degrees:')
# print (sorted(
# [len(list(cg.triples([None, None, node]))) for node in cg.all_nodes()]))
# print(cg.serialize(format='n3'))
assert len(g.all_nodes()) == len(cg.all_nodes())
cg = to_canonical_graph(g)
assert len(g) == len(cg), "canonicalization changed number of triples in graph"
assert len(g.all_nodes()) == len(
cg.all_nodes()
), "canonicalization changed number of nodes in graph"
assert len(list(g.subjects(RDF["type"], RDF["Statement"]))) == len(
list(cg.subjects(RDF["type"], RDF["Statement"]))
), "canonicalization changed number of statements"
# counter for subject, predicate and object nodes
g_pos_counts = Counter(), Counter(), Counter()
for t in g:
for i, node in enumerate(t):
g_pos_counts[i][t] += 1
g_count_signature = [sorted(c.values()) for c in g_pos_counts]
cg_pos_counts = Counter(), Counter(), Counter()
for t in cg:
for i, node in enumerate(t):
cg_pos_counts[i][t] += 1
cg_count_signature = [sorted(c.values()) for c in cg_pos_counts]
assert (
g_count_signature == cg_count_signature
), "canonicalization changed node position counts"
_Triple = Tuple[Node, Node, Node]
_TripleSet = Set[_Triple]
class TestConsistency(unittest.TestCase):
@expectedFailure
def test_consistent_ids(self) -> None:
"""
This test verifies that `to_canonical_graph` creates consistent
identifiers for blank nodes even when the graph changes.
It does this by creating two triple sets `g0_ts` and `g1_ts`
and then first creating a canonical graph with only the first
triple set (cg0), and then a canonical graph with both triple
sets (cg1), and then confirming the triples in cg0 is a subset
of cg1.
This will fail if the `to_canonical_graph` does not generate
consistent identifiers for blank nodes when the graph changes.
This property is essential for `to_canonical_graph` to
be useful for diffing graphs.
"""
bnode = BNode()
g0_ts: _TripleSet = {
(bnode, FOAF.name, Literal("Golan Trevize")),
(bnode, RDF.type, FOAF.Person),
}
bnode = BNode()
g1_ts: _TripleSet = {
(bnode, FOAF.name, Literal("Janov Pelorat")),
(bnode, RDF.type, FOAF.Person),
}
g0 = Graph()
g0 += g0_ts
cg0 = to_canonical_graph(g0)
cg0_ts = GraphHelper.triple_set(cg0)
g1 = Graph()
g1 += g1_ts
cg1 = to_canonical_graph(g1)
cg1_ts = GraphHelper.triple_set(cg1)
assert cg0_ts.issubset(
cg1_ts
), "canonical triple set cg0_ts should be a subset of canonical triple set cg1_ts"
if __name__ == "__main__":
unittest.main()
|