Skip to content

Commit ac36c88

Browse files
committed
implement __hash__() in OverrideRule to easily identify uniqueness
1 parent de5563a commit ac36c88

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

tests/test_overrides.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,35 @@
1717
PONestedModuleOverridenSecondary,
1818
)
1919
from web_poet import PageObjectRegistry, default_registry, registry_pool
20+
from web_poet.overrides import OverrideRule
2021

2122

2223
POS = {POTopLevel1, POTopLevel2, POModule, PONestedPkg, PONestedModule}
2324

2425

26+
def test_override_rule_uniqueness():
27+
"""The same instance of an OverrideRule with the same attribute values should
28+
have the same hash identity.
29+
"""
30+
31+
patterns = Patterns(include=["example.com"], exclude=["example.com/blog"])
32+
33+
rule1 = OverrideRule(
34+
for_patterns=patterns,
35+
use=POTopLevel1,
36+
instead_of=POTopLevelOverriden2,
37+
meta={"key_1": 1}
38+
)
39+
rule2 = OverrideRule(
40+
for_patterns=patterns,
41+
use=POTopLevel1,
42+
instead_of=POTopLevelOverriden2,
43+
meta={"key_2": 2}
44+
)
45+
46+
assert hash(rule1) == hash(rule2)
47+
48+
2549
def test_list_page_objects_all():
2650
rules = default_registry.get_overrides()
2751
page_objects = {po.use for po in rules}

web_poet/overrides.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,26 @@
1515
@dataclass
1616
class OverrideRule:
1717
"""A single override rule that specifies when a Page Object should be used
18-
instead of another."""
18+
instead of another.
19+
"""
1920

2021
for_patterns: Patterns
2122
use: Callable
2223
instead_of: Callable
2324
meta: Dict[str, Any] = field(default_factory=dict)
2425

26+
def __hash__(self):
27+
# TODO: Remove this when the following has been implemented:
28+
# - https://github.com/zytedata/url-matcher/issues/3
29+
pattern_hash = hash(
30+
(
31+
tuple(self.for_patterns.include),
32+
tuple(self.for_patterns.exclude),
33+
self.for_patterns.priority,
34+
)
35+
)
36+
return hash((pattern_hash, self.use, self.instead_of))
37+
2538

2639
def _as_list(value: Optional[Strings]) -> List[str]:
2740
"""

0 commit comments

Comments
 (0)