def __init__(self, name=None, element=None, ns=None, nsmap=dict(), idattribute='id', path=None): self.format = 0 self.outpath = path self.element = element if self.element is None and path is not None: self.element = etree.Element(name, nsmap=nsmap) alsoProvides(self, IRoot) self.namespaces = nsmap self.idattribute = idattribute _ns, _name = self._extractname(self.element) if not name: name = _name if not ns: ns = _ns if ns: self.prefix = '{%s}' % ns else: self.prefix = '' self.ns = ns OrderedNode.__init__(self, name=name) if element is None: return if etree.iselement(element): fq = '%s%s' % (self.prefix, name) if element.tag != fq: raise ValueError, \ 'Fq of given element does not match (%s != %s)' \ % (element.tag, fq) children = self.element.getchildren() else: children = [element.getroot()] self._buildchildren(children)
def __getitem__(self, name): # XXX: use UUID here for tree representation and provide ``children`` # function for filtering by tag name and similar. keys = self._parsekeys(name) if not keys: raise KeyError(u"Node not found") if len(keys) == 1: return OrderedNode.__getitem__(self, keys[0]) return [OrderedNode.__getitem__(self, key) for key in keys]
def __setitem__(self, key, val): name = '%s%s' % (val.prefix, val.__name__) if val.element is None: val.element = etree.SubElement(self.element, name) name = '%s:%s' % (val.uuid, name) id = val.attributes.get(val.idattribute, None) if id: self.refindex[id] = val OrderedNode.__setitem__(self, name, val)
def __init__(self, name, astnode=None, buffer=[]): OrderedNode.__init__(self, name) self.astnode = astnode self.buffer = buffer self.bufstart = None self.bufend = None self.readlines = None self.postlf = 0 if astnode is not None and hasattr(self.astnode, "lineno"): self.bufstart = self.astnode.lineno - 1 self.bufend = self.astnode.lineno
def __init__(self, name, astnode=None, buffer=[]): OrderedNode.__init__(self, name) self.astnode = astnode self.buffer = buffer self.bufstart = None self.bufend = None self.readlines = None self.postlf = 0 if astnode is not None and hasattr(self.astnode, 'lineno'): self.bufstart = self.astnode.lineno - 1 self.bufend = self.astnode.lineno
def test_children(self): # Node children serializition node = OrderedNode(name='base') node['child'] = OrderedNode() node['child']['sub'] = OrderedNode() self.assertEqual(node.treerepr(), ( '<class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child\n' ' <class \'node.base.OrderedNode\'>: sub\n' )) json_data = serialize(node) data = json.loads(json_data) self.assertEqual(list(data.keys()), ['__node__']) node_data = data['__node__'] self.assertEqual( list(sorted(node_data.keys())), ['children', 'class', 'name'] ) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'base') self.assertEqual(len(node_data['children']), 1) node_data = node_data['children'][0]['__node__'] self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'child') self.assertEqual(len(node_data['children']), 1) node_data = node_data['children'][0]['__node__'] self.assertEqual(list(sorted(node_data.keys())), ['class', 'name']) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'sub') node = deserialize(json_data) self.assertEqual(node.treerepr(), ( '<class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child\n' ' <class \'node.base.OrderedNode\'>: sub\n' )) # Deserialize using given root node root = BaseNode(name='root') node = deserialize(json_data, root=root) self.assertEqual(root.treerepr(), ( '<class \'node.base.BaseNode\'>: root\n' ' <class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child\n' ' <class \'node.base.OrderedNode\'>: sub\n' ))
def __init__(self, name, paths): OrderedNode.__init__(self, name) self.xmi = None factory = getUtility(IXMLFactory) for path in paths: buf = self._extract_from_archive(path) # XXX: fix this id stuff in node.ext.xml if buf: xml = factory(path, 'id', buf, nsprefix='xmi') else: xml = factory(path, 'id', nsprefix='xmi') self[path] = xml
def __init__(self, name=None, parent=None, nsmap=None, model=None): OrderedNode.__init__(self, name=name) self.model = model if self.model is not None: self.model.format = 1 if nsmap is None: self.nsmap = self.model.element.nsmap elif parent is not None: self.nsmap = parent.model.element.nsmap parent[self.uuid] = self elif nsmap is not None: self.nsmap = nsmap else: self.nsmap = { None: 'http://namespaces.zope.org/zope', }
def __setitem__(self, key, value): if not IZCMLNode.providedBy(value): raise ValueError(u"Invalid value %s" % value) if value.nsmap is None: value.nsmap = self.nsmap if value.model is None: if value.__name__ is None: raise ValueError(u"Cannot create model. no name given" % value) ns = None if value.__name__.find(':') != -1: ns, name = value.__name__.split(':') else: name = value.__name__ value.model = XMLNode(name, ns=value.nsmap[ns], nsmap=value.nsmap) #value.model.element.nsmap = self.nsmap self.model[value.uuid] = value.model OrderedNode.__setitem__(self, key, value)
def test_OrderedNode(self): self.assertEqual(OrderedNode.__bases__, (object, )) orderednode = OrderedNode() self.assertTrue( str(orderednode).startswith('<OrderedNode object \'None\' at')) fmtester = FullMappingTester(OrderedNode) fmtester.run() self.checkOutput( """\ ``__contains__``: OK ``__delitem__``: OK ``__getitem__``: OK ``__iter__``: OK ``__len__``: OK ``__setitem__``: OK ``clear``: OK ``copy``: OK ``get``: OK ``has_key``: OK ``items``: OK ``iteritems``: OK ``iterkeys``: OK ``itervalues``: OK ``keys``: OK ``pop``: OK ``popitem``: OK ``setdefault``: OK ``update``: OK ``values``: OK """, fmtester.combined) orderednode['child'] = OrderedNode() self.checkOutput( """\ <class 'node.base.OrderedNode'>: None __<class 'node.base.OrderedNode'>: child """, orderednode.treerepr(prefix='_')) unpickled = pickle.loads(pickle.dumps(orderednode)) self.checkOutput( """\ <class 'node.base.OrderedNode'>: None __<class 'node.base.OrderedNode'>: child """, unpickled.treerepr(prefix='_'))
def test_OrderedNode(self): self.assertEqual(OrderedNode.__bases__, (object,)) orderednode = OrderedNode() self.assertTrue( str(orderednode).startswith('<OrderedNode object \'None\' at') ) fmtester = FullMappingTester(OrderedNode) fmtester.run() self.check_output("""\ ``__contains__``: OK ``__delitem__``: OK ``__getitem__``: OK ``__iter__``: OK ``__len__``: OK ``__setitem__``: OK ``clear``: OK ``copy``: OK ``get``: OK ``has_key``: OK ``items``: OK ``iteritems``: OK ``iterkeys``: OK ``itervalues``: OK ``keys``: OK ``pop``: OK ``popitem``: OK ``setdefault``: OK ``update``: OK ``values``: OK """, fmtester.combined) orderednode['child'] = OrderedNode() self.check_output("""\ <class 'node.base.OrderedNode'>: None <class 'node.base.OrderedNode'>: child """, orderednode.treerepr()) unpickled = pickle.loads(pickle.dumps(orderednode)) self.check_output("""\ <class 'node.base.OrderedNode'>: None <class 'node.base.OrderedNode'>: child """, unpickled.treerepr())
def test_children_as_list(self): # Serialize list of nodes node = OrderedNode(name='base') node['child_1'] = OrderedNode() node['child_2'] = OrderedNode() self.assertEqual(node.treerepr(), ( '<class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child_1\n' ' <class \'node.base.OrderedNode\'>: child_2\n' )) json_data = serialize(node.values()) data = json.loads(json_data) self.assertTrue(isinstance(data, list)) self.assertEqual(len(data), 2) node_data = data[0]['__node__'] self.assertEqual(list(sorted(node_data.keys())), ['class', 'name']) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'child_1') node_data = data[1]['__node__'] self.assertEqual(list(sorted(node_data.keys())), ['class', 'name']) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'child_2') # Deserialize list of nodes using given root node root = OrderedNode(name='root') nodes = deserialize(json_data, root=root) self.assertEqual(len(nodes), 2) self.check_output("""\ [<OrderedNode object 'child_1' at ...>, <OrderedNode object 'child_2' at ...>] """, str(nodes)) self.assertEqual(root.treerepr(), ( '<class \'node.base.OrderedNode\'>: root\n' ' <class \'node.base.OrderedNode\'>: child_1\n' ' <class \'node.base.OrderedNode\'>: child_2\n' ))
def test_children_as_list(self): # Serialize list of nodes node = OrderedNode(name='base') node['child_1'] = OrderedNode() node['child_2'] = OrderedNode() self.assertEqual(node.treerepr(), ('<class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child_1\n' ' <class \'node.base.OrderedNode\'>: child_2\n')) json_data = serialize(node.values()) data = json.loads(json_data) self.assertTrue(isinstance(data, list)) self.assertEqual(len(data), 2) node_data = data[0]['__node__'] self.assertEqual(list(sorted(node_data.keys())), ['class', 'name']) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'child_1') node_data = data[1]['__node__'] self.assertEqual(list(sorted(node_data.keys())), ['class', 'name']) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'child_2') # Deserialize list of nodes using given root node root = OrderedNode(name='root') nodes = deserialize(json_data, root=root) self.assertEqual(len(nodes), 2) self.check_output( """\ [<OrderedNode object 'child_1' at ...>, <OrderedNode object 'child_2' at ...>] """, str(nodes)) self.assertEqual(root.treerepr(), ('<class \'node.base.OrderedNode\'>: root\n' ' <class \'node.base.OrderedNode\'>: child_1\n' ' <class \'node.base.OrderedNode\'>: child_2\n'))
def test_children(self): # Node children serializition node = OrderedNode(name='base') node['child'] = OrderedNode() node['child']['sub'] = OrderedNode() self.assertEqual(node.treerepr(), ('<class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child\n' ' <class \'node.base.OrderedNode\'>: sub\n')) json_data = serialize(node) data = json.loads(json_data) self.assertEqual(list(data.keys()), ['__node__']) node_data = data['__node__'] self.assertEqual(list(sorted(node_data.keys())), ['children', 'class', 'name']) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'base') self.assertEqual(len(node_data['children']), 1) node_data = node_data['children'][0]['__node__'] self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'child') self.assertEqual(len(node_data['children']), 1) node_data = node_data['children'][0]['__node__'] self.assertEqual(list(sorted(node_data.keys())), ['class', 'name']) self.assertEqual(node_data['class'], 'node.base.OrderedNode') self.assertEqual(node_data['name'], 'sub') node = deserialize(json_data) self.assertEqual(node.treerepr(), ('<class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child\n' ' <class \'node.base.OrderedNode\'>: sub\n')) # Deserialize using given root node root = BaseNode(name='root') node = deserialize(json_data, root=root) self.assertEqual(root.treerepr(), ('<class \'node.base.BaseNode\'>: root\n' ' <class \'node.base.OrderedNode\'>: base\n' ' <class \'node.base.OrderedNode\'>: child\n' ' <class \'node.base.OrderedNode\'>: sub\n'))
def values(self): # XXX: see __getitem__ return [OrderedNode.__getitem__(self, key) for key in self.keys()]
def __delitem__(self, key): todelete = self[key] self.model.element.remove(todelete.model.element) OrderedNode.__delitem__(self, key)
def __setitem__(self, key, val): if not IXMLNode.providedBy(val) or not IRoot.providedBy(val): raise ValueError(u"Could only contain complete XML trees.") noLongerProvides(val, IRoot) OrderedNode.__setitem__(self, key, val)
def test_INode(self): # XXX: make tester object for INode contract # XXX: decide wether ``aliases`` or ``aliaser`` (still dunno) should be # kept in base interface. # printtree mynode = create_tree(MyNode) self.checkOutput( """\ <class 'node.testing.env.MyNode'>: None __<class 'node.testing.env.MyNode'>: child_0 ____<class 'node.testing.env.MyNode'>: subchild_0 ____<class 'node.testing.env.MyNode'>: subchild_1 __<class 'node.testing.env.MyNode'>: child_1 ____<class 'node.testing.env.MyNode'>: subchild_0 ____<class 'node.testing.env.MyNode'>: subchild_1 __<class 'node.testing.env.MyNode'>: child_2 ____<class 'node.testing.env.MyNode'>: subchild_0 ____<class 'node.testing.env.MyNode'>: subchild_1 """, mynode.treerepr(prefix='_')) basenode = create_tree(BaseNode) self.checkOutput( """\ <class 'node.base.BaseNode'>: None __<class 'node.base.BaseNode'>: child_... ____<class 'node.base.BaseNode'>: subchild_... ____<class 'node.base.BaseNode'>: subchild_... __<class 'node.base.BaseNode'>: child_... ____<class 'node.base.BaseNode'>: subchild_... ____<class 'node.base.BaseNode'>: subchild_... __<class 'node.base.BaseNode'>: child_... ____<class 'node.base.BaseNode'>: subchild_... ____<class 'node.base.BaseNode'>: subchild_... """, basenode.treerepr(prefix='_')) orderednode = create_tree(OrderedNode) self.checkOutput( """\ <class 'node.base.OrderedNode'>: None __<class 'node.base.OrderedNode'>: child_0 ____<class 'node.base.OrderedNode'>: subchild_0 ____<class 'node.base.OrderedNode'>: subchild_1 __<class 'node.base.OrderedNode'>: child_1 ____<class 'node.base.OrderedNode'>: subchild_0 ____<class 'node.base.OrderedNode'>: subchild_1 __<class 'node.base.OrderedNode'>: child_2 ____<class 'node.base.OrderedNode'>: subchild_0 ____<class 'node.base.OrderedNode'>: subchild_1 """, orderednode.treerepr(prefix='_')) # path mynode.__name__ = 'root' self.assertEqual(mynode.path, ['root']) self.assertEqual(mynode['child_1']['subchild_1'].path, ['root', 'child_1', 'subchild_1']) basenode.__name__ = 'root' self.assertEqual(basenode.path, ['root']) self.assertEqual(basenode['child_1']['subchild_1'].path, ['root', 'child_1', 'subchild_1']) orderednode.__name__ = 'root' self.assertEqual(orderednode.path, ['root']) self.assertEqual(orderednode['child_1']['subchild_1'].path, ['root', 'child_1', 'subchild_1']) # root self.assertTrue(mynode['child_1']['subchild_1'].root is mynode) self.assertTrue(basenode['child_1']['subchild_1'].root is basenode) self.assertTrue( orderednode['child_1']['subchild_1'].root is orderednode) # allow_non_node_childs self.assertFalse(mynode.allow_non_node_childs) def non_node_childs_not_allowed(): mynode['foo'] = object() err = self.expectError(ValueError, non_node_childs_not_allowed) self.assertEqual(str(err), 'Non-node childs are not allowed.') def no_classes_as_values_allowed(): mynode['foo'] = object err = self.expectError(ValueError, no_classes_as_values_allowed) expected = 'It isn\'t allowed to use classes as values.' self.assertEqual(str(err), expected) mynode.allow_non_node_childs = True obj = mynode['foo'] = object() self.assertEqual(mynode['foo'], obj) del mynode['foo'] mynode.allow_non_node_childs = False self.assertFalse(basenode.allow_non_node_childs) def non_node_childs_not_allowed2(): basenode['foo'] = object() err = self.expectError(ValueError, non_node_childs_not_allowed2) self.assertEqual(str(err), 'Non-node childs are not allowed.') def no_classes_as_values_allowed2(): basenode['foo'] = object err = self.expectError(ValueError, no_classes_as_values_allowed2) expected = 'It isn\'t allowed to use classes as values.' self.assertEqual(str(err), expected) basenode.allow_non_node_childs = True obj = basenode['foo'] = object() self.assertEqual(basenode['foo'], obj) del basenode['foo'] basenode.allow_non_node_childs = False self.assertFalse(orderednode.allow_non_node_childs) def non_node_childs_not_allowed3(): orderednode['foo'] = object() err = self.expectError(ValueError, non_node_childs_not_allowed3) self.assertEqual(str(err), 'Non-node childs are not allowed.') def no_classes_as_values_allowed3(): orderednode['foo'] = object err = self.expectError(ValueError, no_classes_as_values_allowed3) expected = 'It isn\'t allowed to use classes as values.' self.assertEqual(str(err), expected) orderednode.allow_non_node_childs = True obj = orderednode['foo'] = object() self.assertEqual(orderednode['foo'], obj) del orderednode['foo'] orderednode.allow_non_node_childs = False # filteredvalues and filtereditervalues class IFilter(Interface): pass directlyProvides(mynode['child_2'], IFilter) self.assertEqual(list(mynode.filtereditervalues(IFilter)), [mynode['child_2']]) self.assertEqual(mynode.filteredvalues(IFilter), [mynode['child_2']]) noLongerProvides(mynode['child_2'], IFilter) self.assertEqual(list(mynode.filtereditervalues(IFilter)), []) self.assertEqual(mynode.filteredvalues(IFilter), []) directlyProvides(basenode['child_2'], IFilter) self.assertEqual(list(basenode.filtereditervalues(IFilter)), [basenode['child_2']]) self.assertEqual(basenode.filteredvalues(IFilter), [basenode['child_2']]) noLongerProvides(basenode['child_2'], IFilter) self.assertEqual(list(basenode.filtereditervalues(IFilter)), []) self.assertEqual(basenode.filteredvalues(IFilter), []) directlyProvides(orderednode['child_2'], IFilter) self.assertEqual(list(orderednode.filtereditervalues(IFilter)), [orderednode['child_2']]) self.assertEqual(orderednode.filteredvalues(IFilter), [orderednode['child_2']]) noLongerProvides(orderednode['child_2'], IFilter) self.assertEqual(list(orderednode.filtereditervalues(IFilter)), []) self.assertEqual(orderednode.filteredvalues(IFilter), []) # as_attribute_access myattrs = mynode.as_attribute_access() self.assertEqual(myattrs.__class__, AttributeAccess) self.assertEqual(myattrs.child_1, mynode['child_1']) myattrs.child_3 = MyNode() self.assertEqual(mynode['child_3'], myattrs.child_3) def no_classes_as_values_allowed4(): myattrs.child_4 = object err = self.expectError(ValueError, no_classes_as_values_allowed4) expected = 'It isn\'t allowed to use classes as values.' self.assertEqual(str(err), expected) baseattrs = basenode.as_attribute_access() self.assertEqual(baseattrs.__class__, AttributeAccess) self.assertEqual(baseattrs.child_1, basenode['child_1']) baseattrs.child_3 = BaseNode() self.assertEqual(basenode['child_3'], baseattrs.child_3) def no_classes_as_values_allowed5(): baseattrs.child_4 = object err = self.expectError(ValueError, no_classes_as_values_allowed5) expected = 'It isn\'t allowed to use classes as values.' self.assertEqual(str(err), expected) orderedattrs = orderednode.as_attribute_access() self.assertEqual(orderedattrs.__class__, AttributeAccess) self.assertEqual(orderedattrs.child_1, orderednode['child_1']) orderedattrs.child_3 = OrderedNode() self.assertEqual(orderednode['child_3'], orderedattrs.child_3) def no_classes_as_values_allowed6(): orderedattrs.child_4 = object err = self.expectError(ValueError, no_classes_as_values_allowed6) expected = 'It isn\'t allowed to use classes as values.' self.assertEqual(str(err), expected)
def items(self): # XXX: see __getitem__ return [(key, OrderedNode.__getitem__(self, key)) for key in self.keys()]
def test_copy(self): node = BaseNode() node['child'] = BaseNode() # Shallow copy of BaseNode copied_node = node.copy() self.checkOutput( """\ <class 'node.base.BaseNode'>: None __<class 'node.base.BaseNode'>: child """, copied_node.treerepr(prefix='_')) self.assertFalse(node is copied_node) self.assertTrue(node['child'] is copied_node['child']) copied_node = copy.copy(node) self.assertFalse(node is copied_node) self.assertTrue(node['child'] is copied_node['child']) # Deep copy of base node copied_node = node.deepcopy() self.checkOutput( """\ <class 'node.base.BaseNode'>: None __<class 'node.base.BaseNode'>: child """, copied_node.treerepr(prefix='_')) self.assertFalse(node is copied_node) self.assertFalse(node['child'] is copied_node['child']) copied_node = copy.deepcopy(node) self.assertFalse(node is copied_node) self.assertFalse(node['child'] is copied_node['child']) # Shallow copy of ordered node node = OrderedNode() node['child'] = OrderedNode() copied_node = node.copy() self.checkOutput( """\ <class 'node.base.OrderedNode'>: None __<class 'node.base.OrderedNode'>: child """, copied_node.treerepr(prefix='_')) self.assertFalse(node is copied_node) self.assertTrue(node['child'] is copied_node['child']) copied_node = copy.copy(node) self.assertFalse(node is copied_node) self.assertTrue(node['child'] is copied_node['child']) # Deep copy of ordered node node = OrderedNode() node['child'] = OrderedNode() copied_node = node.deepcopy() self.checkOutput( """\ <class 'node.base.OrderedNode'>: None __<class 'node.base.OrderedNode'>: child """, copied_node.treerepr(prefix='_')) self.assertFalse(node is copied_node) self.assertFalse(node['child'] is copied_node['child']) copied_node = copy.deepcopy(node) self.assertFalse(node is copied_node) self.assertFalse(node['child'] is copied_node['child'])