Skip to content

Commit

Permalink
implement __hash__() in OverrideRule to easily identify uniqueness
Browse files Browse the repository at this point in the history
  • Loading branch information
BurnzZ committed Jan 13, 2022
1 parent de5563a commit ac36c88
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
24 changes: 24 additions & 0 deletions tests/test_overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,35 @@
PONestedModuleOverridenSecondary,
)
from web_poet import PageObjectRegistry, default_registry, registry_pool
from web_poet.overrides import OverrideRule


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


def test_override_rule_uniqueness():
"""The same instance of an OverrideRule with the same attribute values should
have the same hash identity.
"""

patterns = Patterns(include=["example.com"], exclude=["example.com/blog"])

rule1 = OverrideRule(
for_patterns=patterns,
use=POTopLevel1,
instead_of=POTopLevelOverriden2,
meta={"key_1": 1}
)
rule2 = OverrideRule(
for_patterns=patterns,
use=POTopLevel1,
instead_of=POTopLevelOverriden2,
meta={"key_2": 2}
)

assert hash(rule1) == hash(rule2)


def test_list_page_objects_all():
rules = default_registry.get_overrides()
page_objects = {po.use for po in rules}
Expand Down
15 changes: 14 additions & 1 deletion web_poet/overrides.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,26 @@
@dataclass
class OverrideRule:
"""A single override rule that specifies when a Page Object should be used
instead of another."""
instead of another.
"""

for_patterns: Patterns
use: Callable
instead_of: Callable
meta: Dict[str, Any] = field(default_factory=dict)

def __hash__(self):
# TODO: Remove this when the following has been implemented:
# - https://github.com/zytedata/url-matcher/issues/3
pattern_hash = hash(
(
tuple(self.for_patterns.include),
tuple(self.for_patterns.exclude),
self.for_patterns.priority,
)
)
return hash((pattern_hash, self.use, self.instead_of))


def _as_list(value: Optional[Strings]) -> List[str]:
"""
Expand Down

0 comments on commit ac36c88

Please sign in to comment.