Skip to content

Commit

Permalink
fix: add __hash__ and __eq__ back to rdflib.paths.Path (#2292)
Browse files Browse the repository at this point in the history
These methods were removed when `@total_ordering` was added, but
`@total_ordering` does not add them, so removing them essentially
removes functionality.

This change adds the methods back and adds tests to ensure they work
correctly.

All path related tests are also moved into one file.

- Closes <#2281>.
- Closes <#2242>.
  • Loading branch information
aucampia committed Mar 21, 2023
1 parent dd44ae1 commit fe1a8f8
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 9 deletions.
6 changes: 6 additions & 0 deletions rdflib/paths.py
Expand Up @@ -229,6 +229,12 @@ def eval(
) -> Iterator[Tuple["_SubjectType", "_ObjectType"]]:
raise NotImplementedError()

def __hash__(self):
return hash(repr(self))

def __eq__(self, other):
return repr(self) == repr(other)

def __lt__(self, other: Any) -> bool:
if not isinstance(other, (Path, Node)):
raise TypeError(
Expand Down
8 changes: 0 additions & 8 deletions test/test_mulpath_n3.py

This file was deleted.

46 changes: 45 additions & 1 deletion test/test_paths_n3.py → test/test_path.py
Expand Up @@ -3,13 +3,15 @@

import pytest

from rdflib import RDF, RDFS, Graph
from rdflib import RDF, RDFS, Graph, URIRef
from rdflib.namespace import DCAT, DCTERMS
from rdflib.paths import (
AlternativePath,
InvPath,
MulPath,
NegatedPath,
OneOrMore,
Path,
SequencePath,
ZeroOrMore,
ZeroOrOne,
Expand Down Expand Up @@ -71,3 +73,45 @@ def test_paths_n3(
logging.debug("path = %s", path)
assert path.n3() == no_nsm
assert path.n3(nsm) == with_nsm


def test_mulpath_n3():
uri = "http://example.com/foo"
n3 = (URIRef(uri) * ZeroOrMore).n3()
assert n3 == "<" + uri + ">*"


@pytest.mark.parametrize(
["lhs", "rhs"],
[
(DCTERMS.temporal / DCAT.endDate, DCTERMS.temporal / DCAT.endDate),
(SequencePath(DCTERMS.temporal, DCAT.endDate), DCTERMS.temporal / DCAT.endDate),
],
)
def test_eq(lhs: Path, rhs: Path) -> None:
logging.debug("lhs = %s/%r, rhs = %s/%r", type(lhs), lhs, type(rhs), rhs)
assert lhs == rhs


@pytest.mark.parametrize(
["lhs", "rhs"],
[
(DCTERMS.temporal / DCAT.endDate, DCTERMS.temporal / DCAT.endDate),
(SequencePath(DCTERMS.temporal, DCAT.endDate), DCTERMS.temporal / DCAT.endDate),
],
)
def test_hash(lhs: Path, rhs: Path) -> None:
logging.debug("lhs = %s/%r, rhs = %s/%r", type(lhs), lhs, type(rhs), rhs)
assert hash(lhs) == hash(rhs)


@pytest.mark.parametrize(
["insert_path", "check_path"],
[
(DCTERMS.temporal / DCAT.endDate, DCTERMS.temporal / DCAT.endDate),
(SequencePath(DCTERMS.temporal, DCAT.endDate), DCTERMS.temporal / DCAT.endDate),
],
)
def test_dict_key(insert_path: Path, check_path: Path) -> None:
d = {insert_path: "foo"}
assert d[check_path] == "foo"

0 comments on commit fe1a8f8

Please sign in to comment.