Updated ElementBase.setup, and added unit tests.

This commit is contained in:
Lance Stout 2010-08-13 12:24:47 -04:00
parent c721fb4126
commit c20fab0f6c
2 changed files with 55 additions and 16 deletions

View file

@ -76,6 +76,38 @@ class ElementBase(object):
self.iterables.append(sub(child, self)) self.iterables.append(sub(child, self))
break break
def setup(self, xml=None):
"""
Initialize the stanza's XML contents.
Will return True if XML was generated according to the stanza's
definition.
Arguments:
xml -- Optional XML object to use for the stanza's content
instead of generating XML.
"""
if self.xml is None:
self.xml = xml
if self.xml is None:
# Generate XML from the stanza definition
for ename in self.name.split('/'):
new = ET.Element("{%s}%s" % (self.namespace, ename))
if self.xml is None:
self.xml = new
else:
last_xml.append(new)
last_xml = new
if self.parent is not None:
self.parent().xml.append(self.xml)
# We had to generate XML
return True
else:
# We did not generate XML
return False
@property @property
def attrib(self): #backwards compatibility def attrib(self): #backwards compatibility
return self return self
@ -159,22 +191,6 @@ class ElementBase(object):
def findall(self, xpath): def findall(self, xpath):
return self.xml.findall(xpath) return self.xml.findall(xpath)
def setup(self, xml=None):
if self.xml is None:
self.xml = xml
if self.xml is None:
for ename in self.name.split('/'):
new = ET.Element("{%(namespace)s}%(name)s" % {'name': self.name, 'namespace': self.namespace})
if self.xml is None:
self.xml = new
else:
self.xml.append(new)
if self.parent is not None:
self.parent().xml.append(self.xml)
return True #had to generate XML
else:
return False
def enable(self, attrib): def enable(self, attrib):
self.initPlugin(attrib) self.initPlugin(attrib)
return self return self

23
tests/test_elementbase.py Normal file
View file

@ -0,0 +1,23 @@
from . sleektest import *
from sleekxmpp.xmlstream.stanzabase import ElementBase
class TestElementBase(SleekTest):
def testExtendedName(self):
"""Test element names of the form tag1/tag2/tag3."""
class TestStanza(ElementBase):
name = "foo/bar/baz"
namespace = "test"
stanza = TestStanza()
self.checkStanza(TestStanza, stanza, """
<foo xmlns="test">
<bar>
<baz />
</bar>
</foo>
""")
suite = unittest.TestLoader().loadTestsFromTestCase(TestElementBase)