Added __setitem__ to SchemaNode, allowing replacement of nodes by

name.
This commit is contained in:
Chris Rossi
2011-08-05 15:10:01 -04:00
parent 6948236ba4
commit a24828719e
3 changed files with 28 additions and 0 deletions

View File

@@ -11,6 +11,12 @@ Unreleased
- ``unflatten`` is implemented. - ``unflatten`` is implemented.
- Added ``__setitem__`` to ``SchemaNode``, allowing replacement of nodes by
name.
- Added ``get_value`` and ``set_value`` methods to ``Schema`` which allow
access and mutation of appstructs using dotted name paths.
0.9.3 (2011-06-23) 0.9.3 (2011-06-23)
------------------ ------------------

View File

@@ -1640,6 +1640,15 @@ class SchemaNode(object):
return node return node
raise KeyError(name) raise KeyError(name)
def __setitem__(self, name, newnode):
""" Replace a subnode by name """
for idx, node in enumerate(self.children[:]):
if node.name == name:
self.children[idx] = newnode
newnode.name = name
return node
raise KeyError(name)
def __iter__(self): def __iter__(self):
""" Iterate over the children nodes of this schema node """ """ Iterate over the children nodes of this schema node """
return iter(self.children) return iter(self.children)

View File

@@ -1935,6 +1935,19 @@ class TestSchemaNode(unittest.TestCase):
node = self._makeOne(None) node = self._makeOne(None)
self.assertRaises(KeyError, node.__delitem__, 'another') self.assertRaises(KeyError, node.__delitem__, 'another')
def test___setitem__success(self):
node = self._makeOne(None)
another = self._makeOne(None, name='another')
node.add(another)
andanother = self._makeOne(None, name='andanother')
node['another'] = andanother
self.assertEqual(node['another'], andanother)
self.assertEqual(andanother.name, 'another')
def test___setitem__failure(self):
node = self._makeOne(None)
self.assertRaises(KeyError, node.__setitem__, 'another', None)
def test___iter__(self): def test___iter__(self):
node = self._makeOne(None) node = self._makeOne(None)
node.children = ['a', 'b', 'c'] node.children = ['a', 'b', 'c']