summaryrefslogtreecommitdiff
path: root/tests/sleektest.py
blob: c7c72410a150149f2cccd81e4178581879ebcf5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2010 Nathanael C. Fritz, Lance J.T. Stout
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

import unittest
import socket
try:
    import queue
except ImportError:
    import Queue as queue

from sleekxmpp import ClientXMPP
from sleekxmpp.stanza import Message, Iq, Presence
from sleekxmpp.xmlstream.stanzabase import registerStanzaPlugin, ET
from sleekxmpp.xmlstream.tostring import tostring


class TestSocket(object):

    """
    A dummy socket that reads and writes to queues instead
    of an actual networking socket.

    Methods:
        nextSent -- Return the next sent stanza.
        recvData -- Make a stanza available to read next.
        recv     -- Read the next stanza from the socket.
        send     -- Write a stanza to the socket.
        makefile -- Dummy call, returns self.
        read     -- Read the next stanza from the socket.
    """

    def __init__(self, *args, **kwargs):
        """
        Create a new test socket.

        Arguments:
            Same as arguments for socket.socket
        """
        self.socket = socket.socket(*args, **kwargs)
        self.recv_queue = queue.Queue()
        self.send_queue = queue.Queue()

    def __getattr__(self, name):
        """
        Return attribute values of internal, dummy socket.

        Some attributes and methods are disabled to prevent the
        socket from connecting to the network.

        Arguments:
            name -- Name of the attribute requested.
        """

        def dummy(*args):
            """Method to do nothing and prevent actual socket connections."""
            return None

        overrides = {'connect': dummy,
                     'close': dummy,
                     'shutdown': dummy}

        return overrides.get(name, getattr(self.socket, name))

    # ------------------------------------------------------------------
    # Testing Interface

    def nextSent(self, timeout=None):
        """
        Get the next stanza that has been 'sent'.

        Arguments:
            timeout -- Optional timeout for waiting for a new value.
        """
        args = {'block': False}
        if timeout is not None:
            args = {'block': True, 'timeout': timeout}
        try:
            return self.send_queue.get(**args)
        except:
            return None

    def recvData(self, data):
        """
        Add data to the receiving queue.

        Arguments:
            data -- String data to 'write' to the socket to be received
                    by the XMPP client.
        """
        self.recv_queue.put(data)

    # ------------------------------------------------------------------
    # Socket Interface

    def recv(self, *args, **kwargs):
        """
        Read a value from the received queue.

        Arguments:
            Placeholders. Same as for socket.Socket.recv.
        """
        return self.read(block=True)

    def send(self, data):
        """
        Send data by placing it in the send queue.

        Arguments:
            data -- String value to write.
        """
        self.send_queue.put(data)

    # ------------------------------------------------------------------
    # File Socket

    def makefile(self, *args, **kwargs):
        """
        File socket version to use with ElementTree.

        Arguments:
            Placeholders, same as socket.Socket.makefile()
        """
        return self

    def read(self, block=True, timeout=None, **kwargs):
        """
        Implement the file socket interface.

        Arguments:
            block   -- Indicate if the read should block until a
                       value is ready.
            timeout -- Time in seconds a block should last before
                       returning None.
        """
        if timeout is not None:
            block = True
        try:
            return self.recv_queue.get(block, timeout)
        except:
            return None


class SleekTest(unittest.TestCase):

    """
    A SleekXMPP specific TestCase class that provides
    methods for comparing message, iq, and presence stanzas.

    Methods:
        Message            -- Create a Message stanza object.
        Iq                 -- Create an Iq stanza object.
        Presence           -- Create a Presence stanza object.
        checkMessage       -- Compare a Message stanza against an XML string.
        checkIq            -- Compare an Iq stanza against an XML string.
        checkPresence      -- Compare a Presence stanza against an XML string.
        streamStart        -- Initialize a dummy XMPP client.
        streamRecv         -- Queue data for XMPP client to receive.
        streamSendMessage  -- Check that the XMPP client sent the given
                              Message stanza.
        streamSendIq       -- Check that the XMPP client sent the given
                              Iq stanza.
        streamSendPresence -- Check taht the XMPP client sent the given
                              Presence stanza.
        streamClose        -- Disconnect the XMPP client.
        fix_namespaces     -- Add top-level namespace to an XML object.
        compare            -- Compare XML objects against each other.
    """

    # ------------------------------------------------------------------
    # Shortcut methods for creating stanza objects

    def Message(self, *args, **kwargs):
        """
        Create a Message stanza.

        Uses same arguments as StanzaBase.__init__

        Arguments:
            xml -- An XML object to use for the Message's values.
        """
        return Message(None, *args, **kwargs)

    def Iq(self, *args, **kwargs):
        """
        Create an Iq stanza.

        Uses same arguments as StanzaBase.__init__

        Arguments:
            xml -- An XML object to use for the Iq's values.
        """
        return Iq(None, *args, **kwargs)

    def Presence(self, *args, **kwargs):
        """
        Create a Presence stanza.

        Uses same arguments as StanzaBase.__init__

        Arguments:
            xml -- An XML object to use for the Iq's values.
        """
        return Presence(None, *args, **kwargs)

    # ------------------------------------------------------------------
    # Methods for comparing stanza objects to XML strings

    def checkMessage(self, msg, xml_string, use_values=True):
        """
        Create and compare several message stanza objects to a
        correct XML string.

        If use_values is False, the test using getStanzaValues() and
        setStanzaValues() will not be used.

        Arguments:
            msg        -- The Message stanza object to check.
            xml_string -- The XML contents to compare against.
            use_values -- Indicates if the test using getStanzaValues
                          and setStanzaValues should be used. Defaults
                          to True.
        """

        self.fix_namespaces(msg.xml, 'jabber:client')
        debug = "Given Stanza:\n%s\n" % tostring(msg.xml)

        xml = ET.fromstring(xml_string)
        self.fix_namespaces(xml, 'jabber:client')

        debug += "XML String:\n%s\n" % tostring(xml)

        msg2 = self.Message(xml)
        debug += "Constructed Stanza:\n%s\n" % tostring(msg2.xml)

        if use_values:
            # Ugly, but need to make sure the type attribute is set.
            msg['type'] = msg['type']
            if xml.attrib.get('type', None) is None:
                xml.attrib['type'] = 'normal'
            msg2['type'] = msg2['type']
            debug += "XML String:\n%s\n" % tostring(xml)

            values = msg2.getStanzaValues()
            msg3 = self.Message()
            msg3.setStanzaValues(values)

            debug += "Second Constructed Stanza:\n%s\n" % tostring(msg3.xml)
            debug = "Three methods for creating stanza do not match:\n" + debug
            self.failUnless(self.compare(xml, msg.xml, msg2.xml, msg3.xml),
                            debug)
        else:
            debug = "Two methods for creating stanza do not match:\n" + debug
            self.failUnless(self.compare(xml, msg.xml, msg2.xml), debug)

    def checkIq(self, iq, xml_string, use_values=True):
        """
        Create and compare several iq stanza objects to a
        correct XML string.

        If use_values is False, the test using getStanzaValues() and
        setStanzaValues() will not be used.

        Arguments:
            iq         -- The Iq stanza object to check.
            xml_string -- The XML contents to compare against.
            use_values -- Indicates if the test using getStanzaValues
                          and setStanzaValues should be used. Defaults
                          to True.
        """

        self.fix_namespaces(iq.xml, 'jabber:client')
        debug = "Given Stanza:\n%s\n" % tostring(iq.xml)

        xml = ET.fromstring(xml_string)
        self.fix_namespaces(xml, 'jabber:client')
        debug += "XML String:\n%s\n" % tostring(xml)

        iq2 = self.Iq(xml)
        debug += "Constructed Stanza:\n%s\n" % tostring(iq2.xml)

        if use_values:
            values = iq.getStanzaValues()
            iq3 = self.Iq()
            iq3.setStanzaValues(values)

            debug += "Second Constructed Stanza:\n%s\n" % tostring(iq3.xml)
            debug = "Three methods for creating stanza do not match:\n" + debug
            self.failUnless(self.compare(xml, iq.xml, iq2.xml, iq3.xml),
                            debug)
        else:
            debug = "Two methods for creating stanza do not match:\n" + debug
            self.failUnless(self.compare(xml, iq.xml, iq2.xml), debug)

    def checkPresence(self, pres, xml_string, use_values=True):
        """
        Create and compare several presence stanza objects to a
        correct XML string.

        If use_values is False, the test using getStanzaValues() and
        setStanzaValues() will not be used.

        Arguments:
            iq         -- The Iq stanza object to check.
            xml_string -- The XML contents to compare against.
            use_values -- Indicates if the test using getStanzaValues
                          and setStanzaValues should be used. Defaults
                          to True.
        """

        self.fix_namespaces(pres.xml, 'jabber:client')

        xml = ET.fromstring(xml_string)
        self.fix_namespaces(xml, 'jabber:client')

        pres2 = self.Presence(xml)

        # Ugly, but 'priority' has a default value and need to make
        # sure it is set
        pres['priority'] = pres['priority']
        pres2['priority'] = pres2['priority']

        debug = "Given Stanza:\n%s\n" % tostring(pres.xml)
        debug += "XML String:\n%s\n" % tostring(xml)
        debug += "Constructed Stanza:\n%s\n" % tostring(pres2.xml)

        if use_values:
            values = pres.getStanzaValues()
            pres3 = self.Presence()
            pres3.setStanzaValues(values)

            debug += "Second Constructed Stanza:\n%s\n" % tostring(pres3.xml)
            debug = "Three methods for creating stanza do not match:\n" + debug
            self.failUnless(self.compare(xml, pres.xml, pres2.xml, pres3.xml),
                            debug)
        else:
            debug = "Two methods for creating stanza do not match:\n" + debug
            self.failUnless(self.compare(xml, pres.xml, pres2.xml), debug)

    # ------------------------------------------------------------------
    # Methods for simulating stanza streams.

    def streamStart(self, mode='client', skip=True):
        """
        Initialize an XMPP client or component using a dummy XML stream.

        Arguments:
            mode -- Either 'client' or 'component'. Defaults to 'client'.
            skip -- Indicates if the first item in the sent queue (the
                    stream header) should be removed. Tests that wish
                    to test initializing the stream should set this to
                    False. Otherwise, the default of True should be used.
        """
        if mode == 'client':
            self.xmpp = ClientXMPP('tester@localhost', 'test')
            self.xmpp.setSocket(TestSocket())

            self.xmpp.state.set('reconnect', False)
            self.xmpp.state.set('is client', True)
            self.xmpp.state.set('connected', True)

            # Must have the stream header ready for xmpp.process() to work
            self.xmpp.socket.recvData(self.xmpp.stream_header)

        self.xmpp.connectTCP = lambda a, b, c, d: True
        self.xmpp.startTLS = lambda: True
        self.xmpp.process(threaded=True)
        if skip:
            # Clear startup stanzas
            self.xmpp.socket.nextSent(timeout=0.01)

    def streamRecv(self, data):
        """
        Pass data to the dummy XMPP client as if it came from an XMPP server.

        Arguments:
            data -- String stanza XML to be received and processed by the
                    XMPP client or component.
        """
        data = str(data)
        self.xmpp.socket.recvData(data)

    def streamSendMessage(self, data, use_values=True, timeout=.1):
        """
        Check that the XMPP client sent the given stanza XML.

        Extracts the next sent stanza and compares it with the given
        XML using checkMessage.

        Arguments:
            data       -- The XML string of the expected Message stanza,
                          or an equivalent stanza object.
            use_values -- Modifies the type of tests used by checkMessage.
            timeout    -- Time in seconds to wait for a stanza before
                          failing the check.
        """
        if isinstance(data, str):
            data = self.Message(xml=ET.fromstring(data))
        sent = self.xmpp.socket.nextSent(timeout)
        self.checkMessage(data, sent, use_values)

    def streamSendIq(self, data, use_values=True, timeout=.1):
        """
        Check that the XMPP client sent the given stanza XML.

        Extracts the next sent stanza and compares it with the given
        XML using checkIq.

        Arguments:
            data       -- The XML string of the expected Iq stanza,
                          or an equivalent stanza object.
            use_values -- Modifies the type of tests used by checkIq.
            timeout    -- Time in seconds to wait for a stanza before
                          failing the check.
        """
        if isinstance(data, str):
            data = self.Iq(xml=ET.fromstring(data))
        sent = self.xmpp.socket.nextSent(timeout)
        self.checkIq(data, sent, use_values)

    def streamSendPresence(self, data, use_values=True, timeout=.1):
        """
        Check that the XMPP client sent the given stanza XML.

        Extracts the next sent stanza and compares it with the given
        XML using checkPresence.

        Arguments:
            data       -- The XML string of the expected Presence stanza,
                          or an equivalent stanza object.
            use_values -- Modifies the type of tests used by checkPresence.
            timeout    -- Time in seconds to wait for a stanza before
                          failing the check.
        """
        if isinstance(data, str):
            data = self.Presence(xml=ET.fromstring(data))
        sent = self.xmpp.socket.nextSent(timeout)
        self.checkPresence(data, sent, use_values)

    def streamClose(self):
        """
        Disconnect the dummy XMPP client.

        Can be safely called even if streamStart has not been called.

        Must be placed in the tearDown method of a test class to ensure
        that the XMPP client is disconnected after an error.
        """
        if hasattr(self, 'xmpp') and self.xmpp is not None:
            self.xmpp.disconnect()
            self.xmpp.socket.recvData(self.xmpp.stream_footer)

    # ------------------------------------------------------------------
    # XML Comparison and Cleanup

    def fix_namespaces(self, xml, ns):
        """
        Assign a namespace to an element and any children that
        don't have a namespace.

        Arguments:
            xml -- The XML object to fix.
            ns  -- The namespace to add to the XML object.
        """
        if xml.tag.startswith('{'):
            return
        xml.tag = '{%s}%s' % (ns, xml.tag)
        for child in xml.getchildren():
            self.fix_namespaces(child, ns)

    def compare(self, xml, *other):
        """
        Compare XML objects.

        Arguments:
            xml   -- The XML object to compare against.
            *other -- The list of XML objects to compare.
        """
        if not other:
            return False

        # Compare multiple objects
        if len(other) > 1:
            for xml2 in other:
                if not self.compare(xml, xml2):
                    return False
            return True

        other = other[0]

        # Step 1: Check tags
        if xml.tag != other.tag:
            return False

        # Step 2: Check attributes
        if xml.attrib != other.attrib:
            return False

        # Step 3: Recursively check children
        for child in xml:
            child2s = other.findall("%s" % child.tag)
            if child2s is None:
                return False
            for child2 in child2s:
                if self.compare(child, child2):
                    break
            else:
                return False

        # Everything matches
        return True