From b22caeb2463477b9ce5402a258f92782c915834d Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Tue, 20 Aug 2019 19:09:21 +0800 Subject: [PATCH] Add basic merkle proofs tests --- .../eth2spec/test/merkle_proofs/__init__.py | 0 .../test/merkle_proofs/test_merkle_proofs.py | 98 +++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 test_libs/pyspec/eth2spec/test/merkle_proofs/__init__.py create mode 100644 test_libs/pyspec/eth2spec/test/merkle_proofs/test_merkle_proofs.py diff --git a/test_libs/pyspec/eth2spec/test/merkle_proofs/__init__.py b/test_libs/pyspec/eth2spec/test/merkle_proofs/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/test_libs/pyspec/eth2spec/test/merkle_proofs/test_merkle_proofs.py b/test_libs/pyspec/eth2spec/test/merkle_proofs/test_merkle_proofs.py new file mode 100644 index 000000000..5e2c4046b --- /dev/null +++ b/test_libs/pyspec/eth2spec/test/merkle_proofs/test_merkle_proofs.py @@ -0,0 +1,98 @@ + +import re +from eth_utils import ( + to_tuple, +) + +from eth2spec.test.context import ( + spec_state_test, + with_all_phases_except, +) +from eth2spec.utils.ssz.ssz_typing import ( + Bytes32, + Container, + List, + uint64, +) + + +class Foo(Container): + x: uint64 + y: List[Bytes32, 2] + +# Tree +# root +# / \ +# x y_root +# / \ +# y_data_root len(y) +# / \ +# / \ / \ +# +# Generalized indices +# 1 +# / \ +# 2 (x) 3 (y_root) +# / \ +# 6 7 +# / \ +# 12 13 + + +@to_tuple +def ssz_object_to_path(start, end): + is_len = False + len_findall = re.findall(r"(?<=len\().*(?=\))", end) + if len_findall: + is_len = True + end = len_findall[0] + + route = '' + if end.startswith(start): + route = end[len(start):] + + segments = route.split('.') + for word in segments: + index_match = re.match(r"(\w+)\[(\d+)]", word) + if index_match: + yield from index_match.groups() + elif len(word): + yield word + if is_len: + yield '__len__' + + +to_path_test_cases = [ + ('foo', 'foo.x', ('x',)), + ('foo', 'foo.x[100].y', ('x', '100', 'y')), + ('foo', 'foo.x[100].y[1].z[2]', ('x', '100', 'y', '1', 'z', '2')), + ('foo', 'len(foo.x[100].y[1].z[2])', ('x', '100', 'y', '1', 'z', '2', '__len__')), +] + + +def test_to_path(): + for test_case in to_path_test_cases: + start, end, expected = test_case + assert ssz_object_to_path(start, end) == expected + + +generalized_index_cases = [ + (Foo, ('x',), 2), + (Foo, ('y',), 3), + (Foo, ('y', 0), 12), + (Foo, ('y', 1), 13), + (Foo, ('y', '__len__'), None), +] + + +@with_all_phases_except(['phase0']) +@spec_state_test +def test_get_generalized_index(spec, state): + for typ, path, generalized_index in generalized_index_cases: + assert spec.get_generalized_index( + typ=typ, + path=path, + ) == generalized_index + yield 'typ', typ + yield 'path', path + yield 'generalized_index', generalized_index