Skip to content

Commit

Permalink
create page_object_for_item() registry method
Browse files Browse the repository at this point in the history
  • Loading branch information
BurnzZ committed Jan 9, 2023
1 parent c53249c commit b699bd8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
22 changes: 22 additions & 0 deletions tests/test_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,28 @@ def test_page_object_for() -> None:
assert not default_registry.page_object_for(cls("https://example.org"))


def test_page_object_for_item() -> None:
# This is not associated with any rule.
class FakeItem:
pass

method = default_registry.page_object_for_item

for cls in [str, RequestUrl, ResponseUrl]:
url = cls("https://example.com")
assert method(url, ProductSimilar) == CustomProductPageNoReturns
assert method(url, Product) == CustomProductPageDataTypeOnly
assert method(url, ProductSeparate) == SeparateProductPage
assert method(url, ProductFewerFields) == LessProductPage
assert method(url, ProductMoreFields) == MoreProductPage

# When there's no rule specifying to return this FakeItem
assert method(url, FakeItem) is None

# When the URL itself doesn't have any ``to_return`` in any of its rules
assert not method(cls("https://example.org"), FakeItem)


def test_from_override_rules_deprecation_using_ApplyRule() -> None:
rules = [
ApplyRule(
Expand Down
17 changes: 17 additions & 0 deletions web_poet/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,23 @@ def page_object_for(self, url: Union[_Url, str]) -> Mapping[Type, Type[ItemPage]
"""
return self._rules_for_url(url, self._item_matchers)

def page_object_for_item(
self, url: Union[_Url, str], item_cls: Type
) -> Optional[Type]:
"""Return the page object class associated with the given URL that's able
to produce the given ``item_cls``.
"""

url = str(url)

matcher = self._item_matchers.get(item_cls)
if matcher:
rule_id = matcher.match(url)
if rule_id is not None:
return self._rules[rule_id].use

return None


def _walk_module(module: str) -> Iterable:
"""Return all modules from a module recursively.
Expand Down

0 comments on commit b699bd8

Please sign in to comment.