Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix traverse_nested when value is not compatible with ItemAdapter #450

Merged
merged 1 commit into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion spidermon/contrib/utils/attributes.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from typing import Any, List

from itemadapter import ItemAdapter


Expand All @@ -14,7 +15,9 @@ def traverse_nested(obj: ItemAdapter, keys: List[str]) -> ItemAdapter:
# Traverse next level of item object
key = keys.pop(0)
current_obj = ItemAdapter(current_obj[key])
except KeyError:
# KeyError: Key does not exist
# TypeError: Key is not compatible with ItemAdapter (None or unsupported type)
except (KeyError, TypeError):
raise KeyError(f'Invalid key "{key}" for {current_obj} in {obj}')

return current_obj
Expand Down
8 changes: 7 additions & 1 deletion tests/contrib/utils/test_attributes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import pytest
from dataclasses import dataclass

import pytest
from itemadapter import ItemAdapter

from spidermon.contrib.utils.attributes import (
get_nested_attribute,
set_nested_attribute,
Expand All @@ -19,6 +20,11 @@ def test_get_nested_attribute():
with pytest.raises(KeyError):
get_nested_attribute(item, "attr1.missing_attribute.attr2")

# Intermiddle attribute is None
item = ItemAdapter({"foo": None})
with pytest.raises(KeyError):
get_nested_attribute(item, "foo.missing_attribute")


def test_set_nested_attribute():
item = ItemAdapter({"foo": None, "attr1": {"attr2": {"attr3": None}}})
Expand Down
Loading