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

allow dict_to_namedtuple to handle empty dict #2867

Merged
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
1 change: 1 addition & 0 deletions newsfragments/2867.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
fix dict_to_namedtuple unable to handle empty dict as input
25 changes: 25 additions & 0 deletions tests/core/utilities/test_abi.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
get_aligned_abi_inputs,
get_tuple_type_str_parts,
map_abi_data,
recursive_dict_to_namedtuple,
)
from web3._utils.normalizers import (
BASE_RETURN_NORMALIZERS,
Expand Down Expand Up @@ -357,3 +358,27 @@ def test_map_abi_data(types, data, funcs, expected):
def test_exact_length_bytes_encoder_raises_on_non_multiples_of_8_bit_size(arg):
with pytest.raises(ValueError, match="multiple of 8"):
_ = ExactLengthBytesEncoder(None, data_byte_size=2, value_bit_size=arg)


@pytest.mark.parametrize(
"input, expected_output",
[
({"a": 1, "b": 2}, "ABIDecodedNamedTuple(a=1, b=2)"),
({"a": 0}, "ABIDecodedNamedTuple(a=0)"),
({"a": None}, "ABIDecodedNamedTuple(a=None)"),
({"a": False}, "ABIDecodedNamedTuple(a=False)"),
({}, "ABIDecodedNamedTuple()"),
({"a": {}}, "ABIDecodedNamedTuple(a=ABIDecodedNamedTuple())"),
({"a": []}, "ABIDecodedNamedTuple(a=[])"),
({"a": [0]}, "ABIDecodedNamedTuple(a=[0])"),
({"a": [{}]}, "ABIDecodedNamedTuple(a=[ABIDecodedNamedTuple()])"),
(
{"a": {"b": {}}},
"ABIDecodedNamedTuple(a=ABIDecodedNamedTuple(b=ABIDecodedNamedTuple()))",
),
],
)
def test_recursive_dict_to_namedtuple(input, expected_output):
named_tuple_output = recursive_dict_to_namedtuple(input)
output_repr = named_tuple_output.__repr__()
assert output_repr == expected_output
2 changes: 1 addition & 1 deletion web3/_utils/abi.py
Original file line number Diff line number Diff line change
Expand Up @@ -957,7 +957,7 @@ def _dict_to_namedtuple(
if not isinstance(value, dict):
return value

keys, values = zip(*value.items())
keys, values = zip(*value.items()) if value else ((), ())
return abi_decoded_namedtuple_factory(keys)(values)

return recursive_map(_dict_to_namedtuple, data)
Expand Down