Пример #1
0
    def test_iq_reply_handlers(self):
        parent = self

        class Handlers(XMPPFeatureHandler):
            # pylint: disable=W0232,R0201,R0903
            @iq_get_stanza_handler(
                XMLPayload, "{http://pyxmpp.jajcus.net/xmlns/test}payload")
            def handler1(self, stanza):
                return parent.reply_iq_get(stanza)

            @iq_set_stanza_handler(
                XMLPayload, "{http://pyxmpp.jajcus.net/xmlns/test}payload")
            def handler2(self, stanza):
                return parent.reply_iq_set(stanza)

        self.proc.setup_stanza_handlers([Handlers()], "post-auth")
        self.process_stanzas(ALL_STANZAS)
        self.assertEqual(self.handlers_called,
                         ["reply_iq_get", "reply_iq_set"])
        self.assertEqual(len(self.stanzas_sent), 2)
        stanza1 = self.stanzas_sent[0]
        self.assertTrue(
            xml_elements_equal(stanza1.as_xml(), ElementTree.XML(IQ2), True))
        stanza2 = self.stanzas_sent[1]
        self.assertTrue(
            xml_elements_equal(stanza2.as_xml(), ElementTree.XML(IQ4), True))
Пример #2
0
 def as_xml(self, parent=None):
     if parent is not None:
         element = ET.SubElement(parent, VCARD_NS + self.TAG)
     else:
         element = ET.Element(VCARD_NS + self.TAG)
     element.text = self.value
     return element
Пример #3
0
 def test_stanza_get_custom_payload(self):
     stanza6 = Stanza(ElementTree.XML(STANZA6))
     payload = stanza6.get_payload(TestPayload)
     self.assertIsInstance(payload, TestPayload)
     self.assertIsNone(payload.data)  # pylint: disable=E1103
     self.assertTrue(
         xml_elements_equal(ElementTree.XML(STANZA6)[0], payload.as_xml()))
Пример #4
0
 def test_stanza_as_xml(self):
     # STANZA1 and STANZA2 won't match as have no namespace
     for xml in (STANZA0, STANZA3, STANZA4, STANZA5):
         stanza = Stanza(ElementTree.XML(xml))
         self.assertTrue(
             xml_elements_equal(stanza.as_xml(), ElementTree.XML(xml),
                                True))
Пример #5
0
 def test_serialize1(self):
     for xml in (STANZA0, STANZA1, STANZA2, STANZA3, STANZA4, STANZA5):
         stanza = Stanza(ElementTree.XML(xml))
         element1 = ElementTree.XML(
             re.sub(r" xmlns='jabber:[^'\":]*'", "", xml))
         element2 = ElementTree.XML(stanza.serialize())
         self.assertTrue(xml_elements_equal(element1, element2, True))
Пример #6
0
 def as_xml(self):
     element = ElementTree.Element(
         u"{http://pyxmpp.jajcus.net/test/ns}element")
     if self.data:
         ElementTree.SubElement(
             element,
             u"{http://pyxmpp.jajcus.net/test/ns}data").text = self.data
     return element
Пример #7
0
 def as_xml(self, parent=None):
     if parent is None:
         element = ET.Element(VCARD_UPDATE_TAG)
     else:
         element = ET.SubElement(parent, VCARD_UPDATE_TAG)
     child = ET.SubElement(element, VCARD_UPDATE_PHOTO_TAG)
     child.text = self.photo
     return element
Пример #8
0
 def as_xml(self, parent=None):
     if parent is not None:
         element = ET.SubElement(parent, VCARD_NS + self.TAG)
     else:
         element = ET.Element(parent, VCARD_NS + self.TAG)
     for tag in self.CHILD_TAGS:
         child = ET.SubElement(element, VCARD_NS + tag)
         child.text = getattr(self, tag.lower())
     return element
Пример #9
0
 def test_stanza_payload(self):
     stanza5 = Stanza(ElementTree.XML(STANZA5))
     payload = stanza5.get_all_payload()
     self.assertEqual(len(payload), 1)
     payload = payload[0]
     self.assertIsInstance(payload, StanzaPayload)
     self.assertIsInstance(payload, XMLPayload)
     self.assertEqual(payload.xml_element_name, "{jabber:iq:version}query")
     self.assertTrue(
         xml_elements_equal(ElementTree.XML(STANZA5)[0], payload.element))
Пример #10
0
 def test_iq_make_result_response(self):
     iq = Iq(ElementTree.XML(IQ1))
     iq2 = iq.make_result_response()
     payload = ElementTree.Element(
         "{http://pyxmpp.jajcus.net/xmlns/test}payload")
     ElementTree.SubElement(payload,
                            "{http://pyxmpp.jajcus.net/xmlns/test}abc")
     payload = XMLPayload(payload)
     iq2.add_payload(payload)
     self.check_iq2(iq2)
Пример #11
0
 def reply_iq_get(self, stanza):
     self.handlers_called.append("reply_iq_get")
     self.assertIsInstance(stanza, Iq)
     self.assertEqual(stanza.stanza_type, "get")
     reply = stanza.make_result_response()
     element = ElementTree.Element(
         "{http://pyxmpp.jajcus.net/xmlns/test}payload")
     ElementTree.SubElement(element,
                            "{http://pyxmpp.jajcus.net/xmlns/test}abc")
     reply.set_payload(element)
     return reply
Пример #12
0
 def test_serialize2(self):
     stanza = Stanza("presence",
                     from_jid=JID('[email protected]/d'),
                     to_jid=JID('[email protected]/h'),
                     stanza_id='666',
                     stanza_type='unavailable')
     xml = stanza.serialize()
     self.assertTrue(
         xml_elements_equal(
             ElementTree.XML(xml),
             ElementTree.XML(STANZA3.replace(" xmlns='jabber:client'",
                                             ""))))
Пример #13
0
 def test_iq_set(self):
     iq = Iq(from_jid=JID("[email protected]/res"),
             to_jid=JID("*****@*****.**"),
             stanza_type="set",
             stanza_id=2)
     payload = ElementTree.Element(
         "{http://pyxmpp.jajcus.net/xmlns/test}payload")
     ElementTree.SubElement(payload,
                            "{http://pyxmpp.jajcus.net/xmlns/test}abc")
     payload = XMLPayload(payload)
     iq.add_payload(payload)
     self.check_iq3(iq)
     xml = iq.as_xml()
     self.check_iq3(Iq(xml))
Пример #14
0
 def test_stanza_attributes(self):
     stanza3 = Stanza(ElementTree.XML(STANZA3))
     self.assertEqual(stanza3.element_name, u"presence")
     self.assertEqual(stanza3.from_jid, JID(u"[email protected]/d"))
     self.assertEqual(stanza3.to_jid, JID(u"[email protected]/h"))
     self.assertEqual(stanza3.stanza_type, u"unavailable")
     self.assertEqual(stanza3.stanza_id, u'666')
Пример #15
0
    def test_auth_fail(self):
        handler = EventRecorder()
        settings = XMPPSettings({
            u"username": u"user",
            u"password": u"bad",
        })
        self.stream = StreamBase(u"jabber:client", None,
                                 [StreamSASLHandler(settings), handler],
                                 settings)
        self.start_transport([handler])
        self.stream.initiate(self.transport)
        self.connect_transport()
        self.server.write(C2S_SERVER_STREAM_HEAD)
        self.server.write(AUTH_FEATURES)
        xml = self.wait(expect=re.compile(br".*(<auth.*</auth>)"))
        self.assertIsNotNone(xml)
        element = ElementTree.XML(xml)
        self.assertEqual(element.tag, "{urn:ietf:params:xml:ns:xmpp-sasl}auth")
        mech = element.get("mechanism")
        self.assertEqual(mech, "PLAIN")
        data = binascii.a2b_base64(element.text.encode("utf-8"))
        self.assertNotEqual(data, b"\000user\000secret")
        self.server.write(
            b"""<failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>
<not-authorized/></failure>""")
        with self.assertRaises(SASLAuthenticationFailed):
            self.wait()
        self.assertFalse(self.stream.authenticated)
        self.server.disconnect()
        self.wait()
        event_classes = [e.__class__ for e in handler.events_received]
        self.assertEqual(event_classes, [
            ConnectingEvent, ConnectedEvent, StreamConnectedEvent,
            GotFeaturesEvent, DisconnectedEvent
        ])
Пример #16
0
 def as_xml(self):
     element = ET.Element(VCARD_TAG)
     for key in VCARD_FIELDS:
         child = getattr(self, key.lower(), None)
         if child:
             child.as_xml(element)
     return element
Пример #17
0
    def test_request(self):
        payload_received = []
        errors_received = []

        def callback(payload):
            payload_received.append(payload)

        def error_callback(stanza):
            errors_received.append(stanza)

        processor = Processor([])
        request_software_version(processor, JID("*****@*****.**"), callback,
                                 error_callback)
        self.assertEqual(len(processor.stanzas_sent), 1)
        request = processor.stanzas_sent[0]
        self.assertIsInstance(request, Iq)
        self.assertEqual(request.stanza_type, "get")
        payload = request.get_payload(VersionPayload)
        self.assertIsNone(payload.name)
        self.assertIsNone(payload.version)
        self.assertIsNone(payload.os_name)
        response = request.make_result_response()
        payload = XMLPayload(ElementTree.XML(IQ2)[0])
        response.set_payload(payload)
        processor.uplink_receive(response)
        self.assertEqual(len(processor.stanzas_sent), 1)
        self.assertEqual(len(payload_received), 1)
        self.assertEqual(len(errors_received), 0)
        payload = payload_received[0]
        self.assertEqual(payload.name, "NAME")
        self.assertEqual(payload.version, "VERSION")
        self.assertEqual(payload.os_name, "OS")
Пример #18
0
 def test_stanza_build(self):
     stanza = Stanza("presence",
                     from_jid=JID('[email protected]/d'),
                     to_jid=JID('[email protected]/h'),
                     stanza_id='666',
                     stanza_type='unavailable')
     self.assertTrue(
         xml_elements_equal(stanza.as_xml(), ElementTree.XML(STANZA3)))
Пример #19
0
 def test_presence_full(self):
     pres = Presence(from_jid=JID("[email protected]/res"),
                     to_jid=JID("*****@*****.**"),
                     stanza_type=None,
                     stanza_id=u"1",
                     show=u"away",
                     status=u"The Status",
                     priority=10)
     payload = ElementTree.Element(
         "{http://pyxmpp.jajcus.net/xmlns/test}payload")
     ElementTree.SubElement(payload,
                            "{http://pyxmpp.jajcus.net/xmlns/test}abc")
     payload = XMLPayload(payload)
     pres.add_payload(payload)
     self.check_presence_full(pres)
     xml = pres.as_xml()
     self.check_presence_full(Presence(xml))
Пример #20
0
 def test_message_full(self):
     msg = Message(
             from_jid = JID("[email protected]/res"),
             to_jid = JID("*****@*****.**"),
             stanza_type = "normal",
             stanza_id = u"1",
             subject = u"Subject",
             body = u"The body",
             thread = u"thread-id")
     payload = ElementTree.Element(
                         "{http://pyxmpp.jajcus.net/xmlns/test}payload")
     ElementTree.SubElement(payload,
                             "{http://pyxmpp.jajcus.net/xmlns/test}abc")
     payload = XMLPayload(payload)
     msg.add_payload(payload)
     self.check_message_full(msg)
     xml = msg.as_xml()
     self.check_message_full(Message(xml))
Пример #21
0
 def test_stanza_from_empty_element(self):
     stanza0 = Stanza(ElementTree.XML(STANZA0))
     self.assertEqual(stanza0.element_name, "presence")
     self.assertEqual(stanza0.from_jid, None)
     self.assertEqual(stanza0.to_jid, None)
     self.assertEqual(stanza0.stanza_type, None)
     self.assertEqual(stanza0.stanza_id, None)
     stanza1 = Stanza(ElementTree.XML(STANZA1))
     self.assertEqual(stanza1.element_name, "presence")
     self.assertEqual(stanza1.from_jid, None)
     self.assertEqual(stanza1.to_jid, None)
     self.assertEqual(stanza1.stanza_type, None)
     self.assertEqual(stanza1.stanza_id, None)
     stanza2 = Stanza(ElementTree.XML(STANZA2))
     self.assertEqual(stanza2.element_name, "message")
     self.assertEqual(stanza2.from_jid, None)
     self.assertEqual(stanza2.to_jid, None)
     self.assertEqual(stanza2.stanza_type, None)
     self.assertEqual(stanza2.stanza_id, None)
Пример #22
0
 def test_bad_request(self):
     provider = VersionProvider()
     processor = Processor([provider])
     stanza = Iq(ElementTree.XML(IQ2))
     stanza.stanza_type = 'set'
     processor.uplink_receive(stanza)
     self.assertEqual(len(processor.stanzas_sent), 1)
     response = processor.stanzas_sent[0]
     self.assertIsInstance(response, Iq)
     self.assertEqual(response.stanza_type, "error")
     self.assertEqual(
         response.error.condition.tag,
         "{urn:ietf:params:xml:ns:xmpp-stanzas}service-unavailable")
Пример #23
0
 def test_stanza_set_custom_payload(self):
     stanza7 = Stanza("iq",
                      from_jid=JID('[email protected]/d'),
                      to_jid=JID('[email protected]/h'),
                      stanza_id='666',
                      stanza_type='get')
     payload = TestPayload(data=u"Test")
     stanza7.set_payload(payload)
     payload1 = stanza7.get_payload(TestPayload)
     self.assertTrue(payload1 is payload)
     self.assertTrue(
         xml_elements_equal(ElementTree.XML(STANZA7), stanza7.as_xml(),
                            True))
Пример #24
0
 def test_defaults(self):
     provider = VersionProvider()
     processor = Processor([provider])
     stanza = Iq(ElementTree.XML(IQ1))
     processor.uplink_receive(stanza)
     self.assertEqual(len(processor.stanzas_sent), 1)
     response = processor.stanzas_sent[0]
     self.assertIsInstance(response, Iq)
     self.assertEqual(response.stanza_type, "result")
     payload = response.get_payload(VersionPayload)
     self.assertIsInstance(payload, VersionPayload)
     self.assertEqual(payload.name, "PyXMPP2")
     self.assertEqual(payload.version, pyxmpp2.version.version)
     expected = u" ".join(
         (platform.system(), platform.release(), platform.machine()))
     self.assertEqual(payload.os_name, expected)
Пример #25
0
    def handle_receipt_request(self, stanza):
        if not self.stream:
            return

        mid = stanza.stanza_id
        if mid:
            x = stanza.get_xml()
            if x.find('{%s}request' % NS) is None:
                # not requested
                return
            response = Message(to_jid=stanza.from_jid)
            payload = ET.Element("{%s}received" % NS, {'id': mid})
            response.set_payload(payload)
            self.stream.send(response)
        # keep handling it
        return False
Пример #26
0
    def test_build_empty(self):
        item = RosterItem(JID("*****@*****.**"))
        self.assertEqual(item.jid, JID("*****@*****.**"))
        self.assertIsNone(item.name)
        self.assertIsNone(item.subscription)
        self.assertIsNone(item.ask)
        self.assertFalse(item.approved)
        self.assertEqual(item.groups, set())
        xml = item.as_xml()
        self.assertEqual(xml.tag, "{jabber:iq:roster}item")
        self.assertEqual(len(xml), 0)
        self.assertEqual(xml.get("jid"), u"*****@*****.**")
        self.assertEqual(xml.get("name"), None)
        self.assertEqual(xml.get("subscription"), None)
        self.assertEqual(xml.get("ask"), None)
        self.assertEqual(xml.get("approved"), None)

        # check if serializable
        self.assertTrue(ElementTree.tostring(xml))
Пример #27
0
 def test_auth(self):
     handler = EventRecorder()
     self.start_transport([handler])
     settings = XMPPSettings({
         u"user_passwords": {
             u"user": u"secret",
         },
         u"sasl_mechanisms": ["SCRAM-SHA-1", "PLAIN"],
     })
     self.stream = StreamBase(u"jabber:client", None,
                              [StreamSASLHandler(settings), handler],
                              settings)
     self.stream.receive(self.transport, self.addr[0])
     self.client.write(C2S_CLIENT_STREAM_HEAD)
     xml = self.wait(
         expect=re.compile(br".*<stream:features>(.*)</stream:features>"))
     self.assertIsNotNone(xml)
     element = ElementTree.XML(xml)
     self.assertEqual(element.tag,
                      "{urn:ietf:params:xml:ns:xmpp-sasl}mechanisms")
     self.assertEqual(element[0].tag,
                      "{urn:ietf:params:xml:ns:xmpp-sasl}mechanism")
     self.assertEqual(element[0].text, "SCRAM-SHA-1")
     self.assertEqual(element[1].tag,
                      "{urn:ietf:params:xml:ns:xmpp-sasl}mechanism")
     self.assertEqual(element[1].text, "PLAIN")
     response = base64.standard_b64encode(b"\000user\000secret")
     self.client.write(
         PLAIN_AUTH.format(response.decode("utf-8")).encode("utf-8"))
     xml = self.wait(expect=re.compile(br".*(<success.*>)"))
     self.assertIsNotNone(xml)
     self.client.write(C2S_CLIENT_STREAM_HEAD)
     xml = self.wait(expect=re.compile(br".*(<stream:stream.*>)"))
     self.assertIsNotNone(xml)
     self.assertTrue(self.stream.peer_authenticated)
     self.client.write(b"</stream:stream>")
     self.client.disconnect()
     self.wait()
     event_classes = [e.__class__ for e in handler.events_received]
     self.assertEqual(event_classes, [
         StreamConnectedEvent, AuthenticatedEvent, StreamRestartedEvent,
         DisconnectedEvent
     ])
Пример #28
0
 def test_custom(self):
     settings = XMPPSettings({
         "software_name": "NAME",
         "software_version": "VERSION",
         "software_os": "OS",
     })
     provider = VersionProvider(settings)
     processor = Processor([provider])
     stanza = Iq(ElementTree.XML(IQ1))
     processor.uplink_receive(stanza)
     self.assertEqual(len(processor.stanzas_sent), 1)
     response = processor.stanzas_sent[0]
     self.assertIsInstance(response, Iq)
     self.assertEqual(response.stanza_type, "result")
     payload = response.get_payload(VersionPayload)
     self.assertIsInstance(payload, VersionPayload)
     self.assertEqual(payload.name, "NAME")
     self.assertEqual(payload.version, "VERSION")
     self.assertEqual(payload.os_name, "OS")
Пример #29
0
 def test_auth(self):
     handler = EventRecorder()
     settings = XMPPSettings({
         u"username": u"user",
         u"password": u"secret",
     })
     self.stream = StreamBase(u"jabber:client", None,
                              [StreamSASLHandler(settings), handler],
                              settings)
     self.start_transport([handler])
     self.stream.initiate(self.transport)
     self.connect_transport()
     self.server.write(C2S_SERVER_STREAM_HEAD)
     self.server.write(AUTH_FEATURES)
     xml = self.wait(expect=re.compile(br".*(<auth.*</auth>)"))
     self.assertIsNotNone(xml)
     element = ElementTree.XML(xml)
     self.assertEqual(element.tag, "{urn:ietf:params:xml:ns:xmpp-sasl}auth")
     mech = element.get("mechanism")
     self.assertEqual(mech, "PLAIN")
     data = binascii.a2b_base64(element.text.encode("utf-8"))
     self.assertEqual(data, b"\000user\000secret")
     self.server.rdata = b""
     self.server.write(
         b"<success xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>")
     stream_start = self.wait(expect=re.compile(br"(<stream:stream[^>]*>)"))
     self.assertIsNotNone(stream_start)
     self.assertTrue(self.stream.authenticated)
     self.server.write(C2S_SERVER_STREAM_HEAD)
     self.server.write(BIND_FEATURES)
     self.server.write(b"</stream:stream>")
     self.server.disconnect()
     self.wait()
     event_classes = [e.__class__ for e in handler.events_received]
     self.assertEqual(event_classes, [
         ConnectingEvent, ConnectedEvent, StreamConnectedEvent,
         GotFeaturesEvent, AuthenticatedEvent, StreamRestartedEvent,
         GotFeaturesEvent, DisconnectedEvent
     ])
Пример #30
0
    def test_build_full(self):
        item = RosterItem(JID("*****@*****.**"), "NAME", ["G1", "G2"],
                                "from", "subscribe", "true")
        self.assertEqual(item.jid, JID("*****@*****.**"))
        self.assertEqual(item.name, "NAME")
        self.assertEqual(item.subscription, "from")
        self.assertEqual(item.ask, "subscribe")
        self.assertTrue(item.approved)
        self.assertEqual(item.groups, set(["G1", "G2"]))
        xml = item.as_xml()
        self.assertEqual(xml.tag, "{jabber:iq:roster}item")
        self.assertEqual(len(xml), 2)
        self.assertEqual(xml.get("jid"), u"*****@*****.**")
        self.assertEqual(xml.get("name"), "NAME")
        self.assertEqual(xml.get("subscription"), "from")
        self.assertEqual(xml.get("ask"), "subscribe")
        self.assertEqual(xml.get("approved"), "true")
        self.assertEqual(xml[0].tag, "{jabber:iq:roster}group")
        self.assertEqual(xml[1].tag, "{jabber:iq:roster}group")
        self.assertEqual(set([xml[0].text, xml[1].text]), set(["G1", "G2"]))

        # check if serializable
        self.assertTrue(ElementTree.tostring(xml))
Пример #31
0
 def test_presence(self):
     element = ElementTree.XML(PRESENCE1)
     stanza = stanza_factory(element)
     self.assertTrue(isinstance(stanza, Presence))
Пример #32
0
 def test_message(self):
     element = ElementTree.XML(MESSAGE1)
     stanza = stanza_factory(element)
     self.assertTrue(isinstance(stanza, Message))