def testItemsEvent(self): """Testing multiple message/pubsub_event/items/item""" msg = self.Message() item = pubsub.EventItem() item2 = pubsub.EventItem() pl = ET.Element('{http://netflint.net/protocol/test}test', { 'failed': '3', 'passed': '24' }) pl2 = ET.Element('{http://netflint.net/protocol/test-other}test', { 'total': '27', 'failed': '3' }) item2['payload'] = pl2 item['payload'] = pl item['id'] = 'abc123' item2['id'] = '123abc' msg['pubsub_event']['items'].append(item) msg['pubsub_event']['items'].append(item2) msg['pubsub_event']['items']['node'] = 'cheese' msg['type'] = 'normal' self.check( msg, """ <message type="normal"> <event xmlns="http://jabber.org/protocol/pubsub#event"> <items node="cheese"> <item id="abc123"> <test xmlns="http://netflint.net/protocol/test" failed="3" passed="24" /> </item> <item id="123abc"> <test xmlns="http://netflint.net/protocol/test-other" failed="3" total="27" /> </item> </items> </event> </message>""")
def testPublish(self): "Testing iq/pubsub/publish stanzas" iq = self.Iq() iq['pubsub']['publish']['node'] = 'thingers' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['publish'].append(item) iq['pubsub']['publish'].append(item2) form = xep_0004.Form() form['type'] = 'submit' form.addField('pubsub#description', ftype='text-single', value='this thing is awesome') iq['pubsub']['publish_options'] = form self.check( iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <publish node="thingers"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </publish> <publish-options> <x xmlns="jabber:x:data" type="submit"> <field var="pubsub#description"> <value>this thing is awesome</value> </field> </x> </publish-options> </pubsub> </iq>""")
def testPublish(self): "Testing iq/pubsub/publish stanzas" iq = self.Iq() iq['pubsub']['publish']['node'] = 'thingers' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['publish'].append(item) iq['pubsub']['publish'].append(item2) form = xep_0004.Form() form['type'] = 'submit' form.addField('pubsub#description', ftype='text-single', value='this thing is awesome') iq['pubsub']['publish_options'] = form self.check(iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <publish node="thingers"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </publish> <publish-options> <x xmlns="jabber:x:data" type="submit"> <field var="pubsub#description"> <value>this thing is awesome</value> </field> </x> </publish-options> </pubsub> </iq>""")
def set_receipt(self, value): self.del_receipt() if value: parent = self.parent() xml = ET.Element("{%s}received" % self.namespace) xml.attrib['id'] = value parent.append(xml)
def testPayload(self): """Test setting Iq stanza payload.""" iq = self.Iq() iq.set_payload(ET.Element('{test}tester')) self.check(iq, """ <iq id="0"> <tester xmlns="test" /> </iq> """, use_values=False)
def testItems(self): "Testing iq/pubsub/items stanzas" iq = self.Iq() iq['pubsub']['items']['node'] = 'crap' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['items'].append(item) iq['pubsub']['items'].append(item2) self.check( iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <items node="crap"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </items> </pubsub> </iq>""")
def _mask_cmp(self, source, mask, use_ns=False, default_ns='__no_ns__'): """Compare an XML object against an XML mask. :param source: The :class:`~xml.etree.ElementTree.Element` XML object to compare against the mask. :param mask: The :class:`~xml.etree.ElementTree.Element` XML object serving as the mask. :param use_ns: Indicates if namespaces should be respected during the comparison. :default_ns: The default namespace to apply to elements that do not have a specified namespace. Defaults to ``"__no_ns__"``. """ if source is None: # If the element was not found. May happen during recursive calls. return False # Convert the mask to an XML object if it is a string. if not hasattr(mask, 'attrib'): try: mask = ET.fromstring(mask) except ExpatError: log.warning("Expat error: %s\nIn parsing: %s", '', mask) mask_ns_tag = "{%s}%s" % (self.default_ns, mask.tag) if source.tag not in [mask.tag, mask_ns_tag]: return False # If the mask includes text, compare it. if mask.text and source.text and \ source.text.strip() != mask.text.strip(): return False # Compare attributes. The stanza must include the attributes # defined by the mask, but may include others. for name, value in mask.attrib.items(): if source.attrib.get(name, "__None__") != value: return False # Recursively check subelements. matched_elements = {} for subelement in mask: matched = False for other in source.findall(subelement.tag): matched_elements[other] = False if self._mask_cmp(other, subelement, use_ns): if not matched_elements.get(other, False): matched_elements[other] = True matched = True if not matched: return False # Everything matches. return True
def testClear(self): """Test clearing a stanza.""" stanza = StanzaBase() stanza['to'] = '*****@*****.**' stanza['payload'] = ET.Element("{foo}foo") stanza.clear() self.assertTrue(stanza['payload'] == [], "Stanza payload was not cleared after calling .clear()") self.assertTrue(str(stanza['to']) == "*****@*****.**", "Stanza attributes were not preserved after calling .clear()")
def testItems(self): "Testing iq/pubsub/items stanzas" iq = self.Iq() iq['pubsub']['items']['node'] = 'crap' payload = ET.fromstring(""" <thinger xmlns="http://andyet.net/protocol/thinger" x="1" y='2'> <child1 /> <child2 normandy='cheese' foo='bar' /> </thinger>""") payload2 = ET.fromstring(""" <thinger2 xmlns="http://andyet.net/protocol/thinger2" x="12" y='22'> <child12 /> <child22 normandy='cheese2' foo='bar2' /> </thinger2>""") item = pubsub.Item() item['id'] = 'asdf' item['payload'] = payload item2 = pubsub.Item() item2['id'] = 'asdf2' item2['payload'] = payload2 iq['pubsub']['items'].append(item) iq['pubsub']['items'].append(item2) self.check(iq, """ <iq id="0"> <pubsub xmlns="http://jabber.org/protocol/pubsub"> <items node="crap"> <item id="asdf"> <thinger xmlns="http://andyet.net/protocol/thinger" y="2" x="1"> <child1 /> <child2 foo="bar" normandy="cheese" /> </thinger> </item> <item id="asdf2"> <thinger2 xmlns="http://andyet.net/protocol/thinger2" y="22" x="12"> <child12 /> <child22 foo="bar2" normandy="cheese2" /> </thinger2> </item> </items> </pubsub> </iq>""")
def tryTostring(self, original='', expected=None, message='', **kwargs): """ Compare the result of calling tostring against an expected result. """ if not expected: expected=original if isinstance(original, str): xml = ET.fromstring(original) else: xml=original result = tostring(xml, **kwargs) self.assertTrue(result == expected, "%s: %s" % (message, result))
def testReply(self): """Test creating a reply stanza.""" stanza = StanzaBase() stanza['to'] = "*****@*****.**" stanza['from'] = "*****@*****.**" stanza['payload'] = ET.Element("{foo}foo") stanza = stanza.reply() self.assertTrue(str(stanza['to'] == "*****@*****.**"), "Stanza reply did not change 'to' attribute.") self.assertTrue(stanza['payload'] == [], "Stanza reply did not empty stanza payload.")
def testPayload(self): """Test the 'payload' interface of StanzaBase.""" stanza = StanzaBase() self.assertTrue(stanza['payload'] == [], "Empty stanza does not have an empty payload.") stanza['payload'] = ET.Element("{foo}foo") self.assertTrue(len(stanza['payload']) == 1, "Stanza contents and payload do not match.") stanza['payload'] = ET.Element('{bar}bar') self.assertTrue(len(stanza['payload']) == 2, "Stanza payload was not appended.") del stanza['payload'] self.assertTrue(stanza['payload'] == [], "Stanza payload not cleared after deletion.") stanza['payload'] = [ET.Element('{foo}foo'), ET.Element('{bar}bar')] self.assertTrue(len(stanza['payload']) == 2, "Adding multiple elements to stanza's payload did not work.")
def tryTostring(self, original='', expected=None, message='', **kwargs): """ Compare the result of calling tostring against an expected result. """ if not expected: expected = original if isinstance(original, str): xml = ET.fromstring(original) else: xml = original result = tostring(xml, **kwargs) self.failUnless(result == expected, "%s: %s" % (message, result))
def match(self, xml): """ Compare a stanza's XML contents to an XPath expression. If the value of :data:`IGNORE_NS` is set to ``True``, then XPath expressions will be matched without using namespaces. :param xml: The :class:`~slixmpp.xmlstream.stanzabase.ElementBase` stanza to compare against. """ if hasattr(xml, 'xml'): xml = xml.xml x = ET.Element('x') x.append(xml) return x.find(self._criteria) is not None
def match(self, xml): """ Compare a stanza's XML contents to an XPath expression. If the value of :data:`IGNORE_NS` is set to ``True``, then XPath expressions will be matched without using namespaces. .. warning:: In Python 2.6 and 3.1 the ElementTree :meth:`~xml.etree.ElementTree.Element.find()` method does not support attribute selectors in the XPath expression. :param xml: The :class:`~slixmpp.xmlstream.stanzabase.ElementBase` stanza to compare against. """ if hasattr(xml, 'xml'): xml = xml.xml x = ET.Element('x') x.append(xml) return x.find(self._criteria) is not None
def setup(self, xml): # Don't create XML for the plugin self.xml = ET.Element('')
def init_parser(self): self.xml_depth = 0 self.xml_root = None # workaround: slixmpp's xmlstream imports wrong type of ElementTree # (imports xml.etree.ElementTree, but stanzabase uses cElementTree) self.parser = ET.XMLPullParser(("start", "end"))
def set_bar(self, value): wrapper = ET.Element("{foo}wrapper") bar = ET.Element("{foo}bar") bar.text = value wrapper.append(bar) self.xml.append(wrapper)
def setup(self, xml=None): self.xml = ET.Element('') return True
def __init__(self, criteria, default_ns='jabber:client'): MatcherBase.__init__(self, criteria) if isinstance(criteria, str): self._criteria = ET.fromstring(self._criteria) self.default_ns = default_ns