This file is indexed.

/usr/share/pyshared/sleekxmpp/test/sleektest.py is in python-sleekxmpp 1.0~beta5-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
"""
    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
try:
    import Queue as queue
except:
    import queue

import sleekxmpp
from sleekxmpp import ClientXMPP, ComponentXMPP
from sleekxmpp.stanza import Message, Iq, Presence
from sleekxmpp.test import TestSocket, TestLiveSocket
from sleekxmpp.xmlstream import ET, register_stanza_plugin
from sleekxmpp.xmlstream import ElementBase, StanzaBase
from sleekxmpp.xmlstream.tostring import tostring
from sleekxmpp.xmlstream.matcher import StanzaPath, MatcherId
from sleekxmpp.xmlstream.matcher import MatchXMLMask, MatchXPath


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.
        check_jid            -- Check a JID and its component parts.
        check                -- Compare a stanza against an XML string.
        stream_start         -- Initialize a dummy XMPP client.
        stream_close         -- Disconnect the XMPP client.
        make_header          -- Create a stream header.
        send_header          -- Check that the given header has been sent.
        send_feature         -- Send a raw XML element.
        send                 -- Check that the XMPP client sent the given
                                generic stanza.
        recv                 -- Queue data for XMPP client to receive, or
                                verify the data that was received from a
                                live connection.
        recv_header          -- Check that a given stream header
                                was received.
        recv_feature         -- Check that a given, raw XML element
                                was recveived.
        fix_namespaces       -- Add top-level namespace to an XML object.
        compare              -- Compare XML objects against each other.
    """

    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)
        self.xmpp = None

    def runTest(self):
        pass

    def parse_xml(self, xml_string):
        try:
            xml = ET.fromstring(xml_string)
            return xml
        except SyntaxError as e:
            if 'unbound' in e.msg:
                known_prefixes = {
                        'stream': 'http://etherx.jabber.org/streams'}

                prefix = xml_string.split('<')[1].split(':')[0]
                if prefix in known_prefixes:
                    xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % (
                            prefix,
                            known_prefixes[prefix],
                            xml_string)
                xml = self.parse_xml(xml_string)
                xml = xml.getchildren()[0]
                return xml
            else:
                self.fail("XML data was mal-formed:\n%s" % xml_string)

    # ------------------------------------------------------------------
    # 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(self.xmpp, *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(self.xmpp, *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(self.xmpp, *args, **kwargs)

    def check_jid(self, jid, user=None, domain=None, resource=None,
                  bare=None, full=None, string=None):
        """
        Verify the components of a JID.

        Arguments:
            jid      -- The JID object to test.
            user     -- Optional. The user name portion of the JID.
            domain   -- Optional. The domain name portion of the JID.
            resource -- Optional. The resource portion of the JID.
            bare     -- Optional. The bare JID.
            full     -- Optional. The full JID.
            string   -- Optional. The string version of the JID.
        """
        if user is not None:
            self.assertEqual(jid.user, user,
                    "User does not match: %s" % jid.user)
        if domain is not None:
            self.assertEqual(jid.domain, domain,
                    "Domain does not match: %s" % jid.domain)
        if resource is not None:
            self.assertEqual(jid.resource, resource,
                    "Resource does not match: %s" % jid.resource)
        if bare is not None:
            self.assertEqual(jid.bare, bare,
                    "Bare JID does not match: %s" % jid.bare)
        if full is not None:
            self.assertEqual(jid.full, full,
                    "Full JID does not match: %s" % jid.full)
        if string is not None:
            self.assertEqual(str(jid), string,
                    "String does not match: %s" % str(jid))

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

    def check(self, stanza, criteria, method='exact',
              defaults=None, use_values=True):
        """
        Create and compare several stanza objects to a correct XML string.

        If use_values is False, tests using stanza.values will not be used.

        Some stanzas provide default values for some interfaces, but
        these defaults can be problematic for testing since they can easily
        be forgotten when supplying the XML string. A list of interfaces that
        use defaults may be provided and the generated stanzas will use the
        default values for those interfaces if needed.

        However, correcting the supplied XML is not possible for interfaces
        that add or remove XML elements. Only interfaces that map to XML
        attributes may be set using the defaults parameter. The supplied XML
        must take into account any extra elements that are included by default.

        Arguments:
            stanza       -- The stanza object to test.
            criteria     -- An expression the stanza must match against.
            method       -- The type of matching to use; one of:
                            'exact', 'mask', 'id', 'xpath', and 'stanzapath'.
                            Defaults to the value of self.match_method.
            defaults     -- A list of stanza interfaces that have default
                            values. These interfaces will be set to their
                            defaults for the given and generated stanzas to
                            prevent unexpected test failures.
            use_values   -- Indicates if testing using stanza.values should
                            be used. Defaults to True.
        """
        if method is None and hasattr(self, 'match_method'):
            method = getattr(self, 'match_method')

        if method != 'exact':
            matchers = {'stanzapath': StanzaPath,
                        'xpath': MatchXPath,
                        'mask': MatchXMLMask,
                        'id': MatcherId}
            Matcher = matchers.get(method, None)
            if Matcher is None:
                raise ValueError("Unknown matching method.")
            test = Matcher(criteria)
            self.failUnless(test.match(stanza),
                    "Stanza did not match using %s method:\n" % method + \
                    "Criteria:\n%s\n" % str(criteria) + \
                    "Stanza:\n%s" % str(stanza))
        else:
            stanza_class = stanza.__class__
            if not isinstance(criteria, ElementBase):
                xml = self.parse_xml(criteria)
            else:
                xml = criteria.xml

            # Ensure that top level namespaces are used, even if they
            # were not provided.
            self.fix_namespaces(stanza.xml, 'jabber:client')
            self.fix_namespaces(xml, 'jabber:client')

            stanza2 = stanza_class(xml=xml)

            if use_values:
                # Using stanza.values will add XML for any interface that
                # has a default value. We need to set those defaults on
                # the existing stanzas and XML so that they will compare
                # correctly.
                default_stanza = stanza_class()
                if defaults is None:
                    known_defaults = {
                        Message: ['type'],
                        Presence: ['priority']
                    }
                    defaults = known_defaults.get(stanza_class, [])
                for interface in defaults:
                    stanza[interface] = stanza[interface]
                    stanza2[interface] = stanza2[interface]
                    # Can really only automatically add defaults for top
                    # level attribute values. Anything else must be accounted
                    # for in the provided XML string.
                    if interface not in xml.attrib:
                        if interface in default_stanza.xml.attrib:
                            value = default_stanza.xml.attrib[interface]
                            xml.attrib[interface] = value

                values = stanza2.values
                stanza3 = stanza_class()
                stanza3.values = values

                debug = "Three methods for creating stanzas do not match.\n"
                debug += "Given XML:\n%s\n" % tostring(xml)
                debug += "Given stanza:\n%s\n" % tostring(stanza.xml)
                debug += "Generated stanza:\n%s\n" % tostring(stanza2.xml)
                debug += "Second generated stanza:\n%s\n" % tostring(stanza3.xml)
                result = self.compare(xml, stanza.xml, stanza2.xml, stanza3.xml)
            else:
                debug = "Two methods for creating stanzas do not match.\n"
                debug += "Given XML:\n%s\n" % tostring(xml)
                debug += "Given stanza:\n%s\n" % tostring(stanza.xml)
                debug += "Generated stanza:\n%s\n" % tostring(stanza2.xml)
                result = self.compare(xml, stanza.xml, stanza2.xml)

            self.failUnless(result, debug)

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

    def stream_disconnect(self):
        """
        Simulate a stream disconnection.
        """
        if self.xmpp:
            self.xmpp.socket.disconnect_error()

    def stream_start(self, mode='client', skip=True, header=None,
                           socket='mock', jid='tester@localhost',
                           password='test', server='localhost',
                           port=5222, plugins=None):
        """
        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.
            socket   -- Either 'mock' or 'live' to indicate if the socket
                        should be a dummy, mock socket or a live, functioning
                        socket. Defaults to 'mock'.
            jid      -- The JID to use for the connection.
                        Defaults to 'tester@localhost'.
            password -- The password to use for the connection.
                        Defaults to 'test'.
            server   -- The name of the XMPP server. Defaults to 'localhost'.
            port     -- The port to use when connecting to the server.
                        Defaults to 5222.
            plugins  -- List of plugins to register. By default, all plugins
                        are loaded.
        """
        if mode == 'client':
            self.xmpp = ClientXMPP(jid, password)
        elif mode == 'component':
            self.xmpp = ComponentXMPP(jid, password,
                                      server, port)
        else:
            raise ValueError("Unknown XMPP connection mode.")

        # We will use this to wait for the session_start event
        # for live connections.
        skip_queue = queue.Queue()

        if socket == 'mock':
            self.xmpp.set_socket(TestSocket())

            # Simulate connecting for mock sockets.
            self.xmpp.auto_reconnect = False
            self.xmpp.is_client = True
            self.xmpp.state._set_state('connected')

            # Must have the stream header ready for xmpp.process() to work.
            if not header:
                header = self.xmpp.stream_header
            self.xmpp.socket.recv_data(header)
        elif socket == 'live':
            self.xmpp.socket_class = TestLiveSocket
            def wait_for_session(x):
                self.xmpp.socket.clear()
                skip_queue.put('started')
            self.xmpp.add_event_handler('session_start', wait_for_session)
            self.xmpp.connect()
        else:
            raise ValueError("Unknown socket type.")

        if plugins is None:
            self.xmpp.register_plugins()
        else:
            for plugin in plugins:
                self.xmpp.register_plugin(plugin)
        self.xmpp.process(threaded=True)
        if skip:
            if socket != 'live':
                # Mark send queue as usable
                self.xmpp.session_started_event.set()
                # Clear startup stanzas
                self.xmpp.socket.next_sent(timeout=1)
                if mode == 'component':
                    self.xmpp.socket.next_sent(timeout=1)
            else:
                skip_queue.get(block=True, timeout=10)

    def make_header(self, sto='',
                          sfrom='',
                          sid='',
                          stream_ns="http://etherx.jabber.org/streams",
                          default_ns="jabber:client",
                          version="1.0",
                          xml_header=True):
        """
        Create a stream header to be received by the test XMPP agent.

        The header must be saved and passed to stream_start.

        Arguments:
            sto        -- The recipient of the stream header.
            sfrom      -- The agent sending the stream header.
            sid        -- The stream's id.
            stream_ns  -- The namespace of the stream's root element.
            default_ns -- The default stanza namespace.
            version    -- The stream version.
            xml_header -- Indicates if the XML version header should be
                          appended before the stream header.
        """
        header = '<stream:stream %s>'
        parts = []
        if xml_header:
            header = '<?xml version="1.0"?>' + header
        if sto:
            parts.append('to="%s"' % sto)
        if sfrom:
            parts.append('from="%s"' % sfrom)
        if sid:
            parts.append('id="%s"' % sid)
        parts.append('version="%s"' % version)
        parts.append('xmlns:stream="%s"' % stream_ns)
        parts.append('xmlns="%s"' % default_ns)
        return header % ' '.join(parts)

    def recv(self, data, defaults=[], method='exact',
             use_values=True, timeout=1):
        """
        Pass data to the dummy XMPP client as if it came from an XMPP server.

        If using a live connection, verify what the server has sent.

        Arguments:
            data         -- If a dummy socket is being used, the XML that is to
                            be received next. Otherwise it is the criteria used
                            to match against live data that is received.
            defaults     -- A list of stanza interfaces with default values that
                            may interfere with comparisons.
            method       -- Select the type of comparison to use for
                            verifying the received stanza. Options are 'exact',
                            'id', 'stanzapath', 'xpath', and 'mask'.
                            Defaults to the value of self.match_method.
            use_values   -- Indicates if stanza comparisons should test using
                            stanza.values. Defaults to True.
            timeout      -- Time to wait in seconds for data to be received by
                            a live connection.
        """
        if self.xmpp.socket.is_live:
            # we are working with a live connection, so we should
            # verify what has been received instead of simulating
            # receiving data.
            recv_data = self.xmpp.socket.next_recv(timeout)
            if recv_data is None:
                self.fail("No stanza was received.")
            xml = self.parse_xml(recv_data)
            self.fix_namespaces(xml, 'jabber:client')
            stanza = self.xmpp._build_stanza(xml, 'jabber:client')
            self.check(stanza, data,
                       method=method,
                       defaults=defaults,
                       use_values=use_values)
        else:
            # place the data in the dummy socket receiving queue.
            data = str(data)
            self.xmpp.socket.recv_data(data)

    def recv_header(self, sto='',
                          sfrom='',
                          sid='',
                          stream_ns="http://etherx.jabber.org/streams",
                          default_ns="jabber:client",
                          version="1.0",
                          xml_header=False,
                          timeout=1):
        """
        Check that a given stream header was received.

        Arguments:
            sto        -- The recipient of the stream header.
            sfrom      -- The agent sending the stream header.
            sid        -- The stream's id. Set to None to ignore.
            stream_ns  -- The namespace of the stream's root element.
            default_ns -- The default stanza namespace.
            version    -- The stream version.
            xml_header -- Indicates if the XML version header should be
                          appended before the stream header.
            timeout    -- Length of time to wait in seconds for a
                          response.
        """
        header = self.make_header(sto, sfrom, sid,
                                  stream_ns=stream_ns,
                                  default_ns=default_ns,
                                  version=version,
                                  xml_header=xml_header)
        recv_header = self.xmpp.socket.next_recv(timeout)
        if recv_header is None:
            raise ValueError("Socket did not return data.")

        # Apply closing elements so that we can construct
        # XML objects for comparison.
        header2 = header + '</stream:stream>'
        recv_header2 = recv_header + '</stream:stream>'

        xml = self.parse_xml(header2)
        recv_xml = self.parse_xml(recv_header2)

        if sid is None:
            # Ignore the id sent by the server since
            # we can't know in advance what it will be.
            if 'id' in recv_xml.attrib:
                del recv_xml.attrib['id']

        # Ignore the xml:lang attribute for now.
        if 'xml:lang' in recv_xml.attrib:
            del recv_xml.attrib['xml:lang']
        xml_ns = 'http://www.w3.org/XML/1998/namespace'
        if '{%s}lang' % xml_ns in recv_xml.attrib:
            del recv_xml.attrib['{%s}lang' % xml_ns]

        if recv_xml.getchildren:
            # We received more than just the header
            for xml in recv_xml.getchildren():
                self.xmpp.socket.recv_data(tostring(xml))

            attrib = recv_xml.attrib
            recv_xml.clear()
            recv_xml.attrib = attrib

        self.failUnless(
            self.compare(xml, recv_xml),
            "Stream headers do not match:\nDesired:\n%s\nReceived:\n%s" % (
                '%s %s' % (xml.tag, xml.attrib),
                '%s %s' % (recv_xml.tag, recv_xml.attrib)))

    def recv_feature(self, data, method='mask', use_values=True, timeout=1):
        """
        """
        if method is None and hasattr(self, 'match_method'):
            method = getattr(self, 'match_method')

        if self.xmpp.socket.is_live:
            # we are working with a live connection, so we should
            # verify what has been received instead of simulating
            # receiving data.
            recv_data = self.xmpp.socket.next_recv(timeout)
            xml = self.parse_xml(data)
            recv_xml = self.parse_xml(recv_data)
            if recv_data is None:
                self.fail("No stanza was received.")
            if method == 'exact':
                self.failUnless(self.compare(xml, recv_xml),
                    "Features do not match.\nDesired:\n%s\nReceived:\n%s" % (
                        tostring(xml), tostring(recv_xml)))
            elif method == 'mask':
                matcher = MatchXMLMask(xml)
                self.failUnless(matcher.match(recv_xml),
                    "Stanza did not match using %s method:\n" % method + \
                    "Criteria:\n%s\n" % tostring(xml) + \
                    "Stanza:\n%s" % tostring(recv_xml))
            else:
                raise ValueError("Uknown matching method: %s" % method)
        else:
            # place the data in the dummy socket receiving queue.
            data = str(data)
            self.xmpp.socket.recv_data(data)

    def send_header(self, sto='',
                          sfrom='',
                          sid='',
                          stream_ns="http://etherx.jabber.org/streams",
                          default_ns="jabber:client",
                          version="1.0",
                          xml_header=False,
                          timeout=1):
        """
        Check that a given stream header was sent.

        Arguments:
            sto        -- The recipient of the stream header.
            sfrom      -- The agent sending the stream header.
            sid        -- The stream's id.
            stream_ns  -- The namespace of the stream's root element.
            default_ns -- The default stanza namespace.
            version    -- The stream version.
            xml_header -- Indicates if the XML version header should be
                          appended before the stream header.
            timeout    -- Length of time to wait in seconds for a
                          response.
        """
        header = self.make_header(sto, sfrom, sid,
                                  stream_ns=stream_ns,
                                  default_ns=default_ns,
                                  version=version,
                                  xml_header=xml_header)
        sent_header = self.xmpp.socket.next_sent(timeout)
        if sent_header is None:
            raise ValueError("Socket did not return data.")

        # Apply closing elements so that we can construct
        # XML objects for comparison.
        header2 = header + '</stream:stream>'
        sent_header2 = sent_header + b'</stream:stream>'

        xml = self.parse_xml(header2)
        sent_xml = self.parse_xml(sent_header2)

        self.failUnless(
            self.compare(xml, sent_xml),
            "Stream headers do not match:\nDesired:\n%s\nSent:\n%s" % (
                header, sent_header))

    def send_feature(self, data, method='mask', use_values=True, timeout=1):
        """
        """
        sent_data = self.xmpp.socket.next_sent(timeout)
        xml = self.parse_xml(data)
        sent_xml = self.parse_xml(sent_data)
        if sent_data is None:
            self.fail("No stanza was sent.")
        if method == 'exact':
            self.failUnless(self.compare(xml, sent_xml),
                "Features do not match.\nDesired:\n%s\nReceived:\n%s" % (
                    tostring(xml), tostring(sent_xml)))
        elif method == 'mask':
            matcher = MatchXMLMask(xml)
            self.failUnless(matcher.match(sent_xml),
                "Stanza did not match using %s method:\n" % method + \
                "Criteria:\n%s\n" % tostring(xml) + \
                "Stanza:\n%s" % tostring(sent_xml))
        else:
            raise ValueError("Uknown matching method: %s" % method)

    def send(self, data, defaults=None, use_values=True,
             timeout=.5, method='exact'):
        """
        Check that the XMPP client sent the given stanza XML.

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

        Arguments:
            stanza_class -- The class of the sent stanza object.
            data         -- The XML string of the expected Message stanza,
                            or an equivalent stanza object.
            use_values   -- Modifies the type of tests used by check_message.
            defaults     -- A list of stanza interfaces that have defaults
                            values which may interfere with comparisons.
            timeout      -- Time in seconds to wait for a stanza before
                            failing the check.
            method       -- Select the type of comparison to use for
                            verifying the sent stanza. Options are 'exact',
                            'id', 'stanzapath', 'xpath', and 'mask'.
                            Defaults to the value of self.match_method.
        """
        sent = self.xmpp.socket.next_sent(timeout)
        if data is None and sent is None:
            return
        if data is None and sent is not None:
            self.fail("Stanza data was sent: %s" % sent)
        if sent is None:
            self.fail("No stanza was sent.")

        xml = self.parse_xml(sent)
        self.fix_namespaces(xml, 'jabber:client')
        sent = self.xmpp._build_stanza(xml, 'jabber:client')
        self.check(sent, data,
                   method=method,
                   defaults=defaults,
                   use_values=use_values)

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

        Can be safely called even if stream_start 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.socket.recv_data(self.xmpp.stream_footer)
            self.xmpp.disconnect()

    # ------------------------------------------------------------------
    # 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: Check text
        if xml.text is None:
            xml.text = ""
        if other.text is None:
            other.text = ""
        xml.text = xml.text.strip()
        other.text = other.text.strip()

        if xml.text != other.text:
            return False

        # Step 4: Check children count
        if len(xml.getchildren()) != len(other.getchildren()):
            return False

        # Step 5: 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

        # Step 6: Recursively check children the other way.
        for child in other:
            child2s = xml.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