edtlib: add Node.child_index()

It can be useful to know what the index of a particular child is in
the list of nodes. Add a a helper for computing that and some test
cases.

Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
This commit is contained in:
Martí Bolívar 2022-03-23 13:22:35 -07:00 committed by Carles Cufí
commit 7c3b445323
3 changed files with 30 additions and 1 deletions

View file

@ -724,6 +724,21 @@ class Node:
return OrderedDict((name, self.edt._node2enode[node])
for name, node in self._node.nodes.items())
def child_index(self, node):
"""Get the index of *node* in self.children.
Raises KeyError if the argument is not a child of this node.
"""
if not hasattr(self, '_child2index'):
# Defer initialization of this lookup table until this
# method is callable to handle parents needing to be
# initialized before their chidlren. By the time we
# return from __init__, 'self.children' is callable.
self._child2index = OrderedDict()
for index, child in enumerate(self.children.values()):
self._child2index[child] = index
return self._child2index[node]
@property
def required_by(self):
"See the class docstring"

View file

@ -310,7 +310,7 @@
};
//
// For testing Node.parent and Node.children
// For testing hierarchy.
//
parent {

View file

@ -158,6 +158,20 @@ def test_hierarchy():
assert edt.get_node("/parent/child-1").children == {}
def test_child_index():
'''Test Node.child_index.'''
with from_here():
edt = edtlib.EDT("test.dts", ["test-bindings"])
parent, child_1, child_2 = [edt.get_node(path) for path in
("/parent",
"/parent/child-1",
"/parent/child-2")]
assert parent.child_index(child_1) == 0
assert parent.child_index(child_2) == 1
with pytest.raises(KeyError):
parent.child_index(parent)
def test_include():
'''Test 'include:' and the legacy 'inherits: !include ...' in bindings'''
with from_here():