File: test_service.py

package info (click to toggle)
python-aioxmpp 0.13.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 6,244 kB
  • sloc: python: 97,761; xml: 215; makefile: 155; sh: 63
file content (796 lines) | stat: -rw-r--r-- 25,050 bytes parent folder | download | duplicates (2)
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
########################################################################
# File name: test_service.py
# This file is part of: aioxmpp
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
import asyncio
import unittest
import unittest.mock

from datetime import timedelta

import aioxmpp
import aioxmpp.xso as xso
import aioxmpp.service as service
import aioxmpp.disco.xso as disco_xso
import aioxmpp.ibb as ibb
import aioxmpp.ibb.service as ibb_service
import aioxmpp.ibb.xso as ibb_xso

from aioxmpp.utils import namespaces

from aioxmpp.testutils import (
    make_connected_client,
    CoroutineMock,
    run_coroutine,
)

TEST_FROM = aioxmpp.structs.JID.fromstr("foo@bar.example/baz")
TEST_JID1 = aioxmpp.structs.JID.fromstr("bar@bar.example/baz")
TEST_JID2 = aioxmpp.structs.JID.fromstr("baz@bar.example/baz")


class TestIBBService(unittest.TestCase):

    def setUp(self):
        self.cc = make_connected_client()
        self.cc.local_jid = TEST_FROM
        self.s = ibb.IBBService(
            self.cc,
        )

    def tearDown(self):
        del self.cc
        del self.s

    def test_is_service(self):
        self.assertTrue(issubclass(
            ibb.IBBService,
            aioxmpp.service.Service
        ))

    def test_open_session_block_size_too_large(self):
        protocol = unittest.mock.Mock()
        with self.assertRaisesRegex(ValueError, r"^block_size too large$"):
            run_coroutine(
                self.s.open_session(protocol, TEST_JID1, block_size=(1<<16)))

    def test_open_session_default(self):
        with unittest.mock.patch("aioxmpp.utils.to_nmtoken")\
             as gsi:
            gsi.return_value = "sentinel"
            protocol = unittest.mock.Mock()
            handle, protocl = run_coroutine(
                self.s.open_session(protocol, TEST_JID1)
            )

        self.assertEqual(
            handle.get_extra_info("sid"),
            "sentinel"
        )

        self.assertEqual(
            handle.get_extra_info("block_size"),
            4096
        )

        self.assertEqual(
            handle.get_extra_info("stanza_type"),
            ibb_xso.IBBStanzaType.IQ
        )

        self.assertEqual(
            handle.get_extra_info("peer_jid"),
            TEST_JID1
        )

        (s, (iq,), kwargs), = self.cc.send.mock_calls
        self.assertFalse(kwargs)
        self.assertEqual(iq.to, TEST_JID1)
        self.assertEqual(iq.payload.sid, "sentinel")
        self.assertEqual(iq.payload.stanza, ibb_xso.IBBStanzaType.IQ)
        self.assertEqual(iq.payload.block_size, 4096)


    def test_open_session_non_default(self):
        with unittest.mock.patch("aioxmpp.utils.to_nmtoken")\
             as gsi:
            gsi.return_value = "sentinel"
            protocol = unittest.mock.Mock()
            handle, proto = run_coroutine(
                self.s.open_session(
                    protocol,
                    TEST_JID1,
                    stanza_type=ibb_xso.IBBStanzaType.MESSAGE,
                    block_size=8192,
                )
            )

        self.assertEqual(
            handle.get_extra_info("sid"),
            "sentinel"
        )

        self.assertEqual(
            handle.get_extra_info("block_size"),
            8192
        )

        self.assertEqual(
            handle.get_extra_info("peer_jid"),
            TEST_JID1
        )

        self.assertEqual(
            handle.get_extra_info("stanza_type"),
            ibb_xso.IBBStanzaType.MESSAGE
        )

        (s, (iq,), kwargs), = self.cc.send.mock_calls
        self.assertFalse(kwargs)
        self.assertEqual(iq.to, TEST_JID1)
        self.assertEqual(iq.payload.sid, "sentinel")
        self.assertEqual(iq.payload.stanza, ibb_xso.IBBStanzaType.MESSAGE)
        self.assertEqual(iq.payload.block_size, 8192)

    def test_open_request_enforce_limit(self):
        open_ = ibb_xso.Open()
        open_.sid = "sentinel"
        open_.block_size = 8192
        open_.stanza = ibb_xso.IBBStanzaType.IQ

        iq = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            payload=open_
        )
        try:
            run_coroutine(self.s._handle_open_request(iq))
        except aioxmpp.errors.XMPPCancelError as e:
            self.assertEqual(
                e.condition,
                aioxmpp.errors.ErrorCondition.NOT_ACCEPTABLE
            )
        else:
            self.fail("missing expected exception")

    def test_open_request_resource_constraint(self):
        open_ = ibb_xso.Open()
        open_.sid = "sentinel"
        open_.block_size = 1<<32
        open_.stanza = ibb_xso.IBBStanzaType.IQ

        iq = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            payload=open_
        )
        try:
            run_coroutine(self.s._handle_open_request(iq))
        except aioxmpp.errors.XMPPModifyError as e:
            self.assertEqual(
                e.condition,
                aioxmpp.errors.ErrorCondition.RESOURCE_CONSTRAINT
            )
        else:
            self.fail("missing expected exception")

    def test_open_request_allowed_limit(self):
        self.s.session_limit = 1
        self.s.default_protocol_factory = unittest.mock.Mock()

        def on_connection_accepted(transport, protocol):
            pass

        self.s.on_session_accepted.connect(
            on_connection_accepted
        )

        open_ = ibb_xso.Open()
        open_.sid = "sentinel"
        open_.block_size = 8192
        open_.stanza = ibb_xso.IBBStanzaType.IQ

        iq = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            payload=open_
        )

        run_coroutine(self.s._handle_open_request(iq))

    def test_open_request_expected_session(self):
        protocol_factory = unittest.mock.Mock()
        s_fut = self.s.expect_session(protocol_factory, TEST_JID1, "sentinel")

        open_ = ibb_xso.Open()
        open_.sid = "sentinel"
        open_.block_size = 8192
        open_.stanza = ibb_xso.IBBStanzaType.IQ

        iq = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            payload=open_
        )
        run_coroutine(self.s._handle_open_request(iq))

        async def await_s_fut():
            return await s_fut

        handle, proto = run_coroutine(await_s_fut())
        self.assertEqual(
            handle.get_extra_info("peer_jid"),
            TEST_JID1
        )
        self.assertEqual(
            handle.get_extra_info("sid"),
            "sentinel"
        )
        self.assertEqual(
            handle.get_extra_info("block_size"),
            8192
        )

        protocol_factory().connection_made.assert_called_with(handle)

    def test_remote_close_unknown_session(self):
        close = ibb_xso.Close()
        close.sid = "quark"
        stanza = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            to=TEST_FROM,
            payload=close
        )
        try:
            run_coroutine(self.s._handle_close_request(stanza))
        except aioxmpp.errors.XMPPCancelError as e:
            self.assertEqual(
                e.condition,
                aioxmpp.errors.ErrorCondition.ITEM_NOT_FOUND
            )

    def test_handle_open_request_is_iq_handler(self):
        self.assertTrue(
            aioxmpp.service.is_iq_handler(
                aioxmpp.IQType.SET,
                ibb_xso.Open,
                ibb_service.IBBService._handle_open_request,
            )
        )

    def test_handle_close_request_is_iq_handler(self):
        self.assertTrue(
            aioxmpp.service.is_iq_handler(
                aioxmpp.IQType.SET,
                ibb_xso.Close,
                ibb_service.IBBService._handle_close_request,
            )
        )

    def test_handle_data_is_iq_handler(self):
        self.assertTrue(
            aioxmpp.service.is_iq_handler(
                aioxmpp.IQType.SET,
                ibb_xso.Data,
                ibb_service.IBBService._handle_data,
            )
        )

class TestProtocol(asyncio.Protocol):

    def __init__(self):
        self.data = b""
        self.data_received_evt = asyncio.Event()
        self.connection_lost_fut = asyncio.Future()
        self._transport = None

    def connection_made(self, transport):
        self._transport = transport

    def connection_lost(self, e):
        self.connection_lost_fut.set_result(e)

    def pause_writing(self):
        pass

    def resume_writing(self):
        pass

    def data_received(self, data):
        self.data += data
        self.data_received_evt.set()

class TestIBBService_OpenConnection(unittest.TestCase):

    def setUp(self):
        self.cc = make_connected_client()
        self.cc.local_jid = TEST_FROM
        self.s = ibb.IBBService(
            self.cc,
        )
        self.s.initial_wait_time = timedelta(milliseconds=1)
        protocol_factory = unittest.mock.Mock()
        self.handle, self.protocol = run_coroutine(
            self.s.open_session(protocol_factory, TEST_JID1)
        )
        self.cc.send.mock_calls.clear()

    def tearDown(self):
        # ensure clean-up
        self.s._on_stream_destroyed()
        del self.cc
        del self.s

    def test_send(self):
        arguments = []
        async def patched_send(stanza):
            fut.set_result(None)
            arguments.append(stanza)

        for i in range(5):
            fut = asyncio.Future()
            self.cc.send = patched_send
            self.handle.write(b"some data")
            run_coroutine(fut)

        total_content = b""
        for i, iq in enumerate(arguments):
            self.assertEqual(iq.to, TEST_JID1)
            self.assertIsInstance(iq.payload, ibb_xso.Data)
            self.assertEqual(iq.payload.sid, self.handle.get_extra_info("sid"))
            self.assertEqual(iq.payload.seq, i)
            self.assertTrue(iq.payload.content)
            total_content += iq.payload.content
        self.assertEqual(total_content, b"some data"*5)

    def test_receive(self):

        proto = TestProtocol()
        self.handle.set_protocol(proto)
        total_text = b""
        for i in range(5):
            text = "data{}".format(i).encode("us-ascii")
            stanza = aioxmpp.IQ(
                aioxmpp.IQType.SET,
                from_=TEST_JID1,
                to=TEST_FROM,
                payload=ibb_xso.Data(
                    self.handle.get_extra_info("sid"),
                    i,
                    text
                )
            )
            total_text += text
            run_coroutine(self.s._handle_data(stanza))

        self.assertEqual(
            proto.data, total_text
        )

    def test_open_request_established_session(self):
        self.s.session_limit = 2
        self.s.default_protocol_factory = unittest.mock.Mock()
        on_session_accepted = unittest.mock.Mock()
        self.s.on_session_accepted.connect(
            on_session_accepted
        )

        open_ = ibb_xso.Open()
        open_.sid = self.handle.get_extra_info("sid")
        open_.block_size = 4096
        open_.stanza = ibb_xso.IBBStanzaType.IQ

        iq = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            payload=open_
        )

        try:
            run_coroutine(self.s._handle_open_request(iq))
        except aioxmpp.errors.XMPPCancelError as e:
            self.assertEqual(
                e.condition,
                aioxmpp.errors.ErrorCondition.NOT_ACCEPTABLE
            )

        self.assertEqual(len(on_session_accepted.mock_calls), 0)

    def test_receive_invalid_session(self):
        proto = TestProtocol()
        self.handle.set_protocol(proto)

        stanza = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            to=TEST_FROM,
            payload=ibb_xso.Data(
                "fnord",
                0,
                b"data",
            )
        )
        try:
            run_coroutine(self.s._handle_data(stanza))
        except aioxmpp.errors.XMPPCancelError as e:
            self.assertEqual(
                e.condition,
                aioxmpp.errors.ErrorCondition.ITEM_NOT_FOUND
            )
        else:
            self.fail("expected exception was not raised")
        self.assertEqual(proto.data, b"")

    def test_receive_invalid_seq(self):
        proto = TestProtocol()
        self.handle.set_protocol(proto)

        stanza = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            to=TEST_FROM,
            payload=ibb_xso.Data(
                self.handle.get_extra_info("sid"),
                1,
                b"data",
            )
        )
        try:
            run_coroutine(self.s._handle_data(stanza))
        except aioxmpp.errors.XMPPCancelError as e:
            self.assertEqual(
                e.condition,
                aioxmpp.errors.ErrorCondition.UNEXPECTED_REQUEST
            )
        else:
            self.fail("expected exception was not raised")
        self.assertEqual(proto.data, b"")

    def test_wait_error_timeout(self):
        fut = asyncio.Future()
        self.protocol.connection_lost = lambda e: fut.set_result(e)
        self.cc.send.side_effect = aioxmpp.errors.XMPPWaitError(
            aioxmpp.errors.ErrorCondition.RECIPIENT_UNAVAILABLE
        )
        self.handle.write(b"data")
        run_coroutine(fut)
        self.assertEqual(self.handle._retries, self.s.max_retries)
        self.assertFalse(self.s._sessions)
        self.assertIsInstance(fut.result(), asyncio.TimeoutError)

    def test_wait_error_recover(self):
        fut = asyncio.Future()
        fut_close = asyncio.Future()

        def side_effect(*args, **kwargs):
            yield aioxmpp.errors.XMPPWaitError(
                aioxmpp.errors.ErrorCondition.RECIPIENT_UNAVAILABLE
            )
            fut.set_result((args, kwargs))
            yield unittest.mock.DEFAULT
            fut_close.set_result((args, kwargs))
            yield unittest.mock.DEFAULT

        self.cc.send.side_effect = side_effect()
        self.handle.write(b"data")
        run_coroutine(fut)
        self.handle.close()
        run_coroutine(fut_close)
        self.assertEqual(self.handle._wait_time,
                         self.s.initial_wait_time.total_seconds())
        self.assertEqual(self.handle._retries, 0)

    def test_remote_seq_error(self):
        fut = asyncio.Future()
        self.protocol.connection_lost = lambda e: fut.set_result(e)
        self.cc.send.side_effect = aioxmpp.errors.XMPPCancelError(
            aioxmpp.errors.ErrorCondition.UNEXPECTED_REQUEST
        )
        self.handle.write(b"data")
        run_coroutine(fut)
        self.assertIs(fut.result(), self.cc.send.side_effect)
        self.assertFalse(self.s._sessions)

        (_, (iq1,), _), (_, (iq2,), _) = self.cc.send.mock_calls
        self.assertEqual(iq1.type_, aioxmpp.IQType.SET)
        self.assertIsInstance(iq1.payload, ibb_xso.Data)
        self.assertEqual(iq2.type_, aioxmpp.IQType.SET)
        self.assertIsInstance(iq2.payload, ibb_xso.Close)

    def test_remote_abort(self):
        fut = asyncio.Future()
        self.protocol.connection_lost = lambda e: fut.set_result(e)
        self.cc.send.side_effect = aioxmpp.errors.XMPPCancelError(
            aioxmpp.errors.ErrorCondition.ITEM_NOT_FOUND
        )
        self.handle.write(b"data")
        run_coroutine(fut)
        self.assertIs(fut.result(), self.cc.send.side_effect)
        self.assertFalse(self.s._sessions)

        (_, (iq1,), _), (_, (iq2,), _) = self.cc.send.mock_calls
        self.assertEqual(iq1.type_, aioxmpp.IQType.SET)
        self.assertIsInstance(iq1.payload, ibb_xso.Data)
        self.assertEqual(iq2.type_, aioxmpp.IQType.SET)
        self.assertIsInstance(iq2.payload, ibb_xso.Close)


    def test_disconnect(self):
        fut = asyncio.Future()
        self.protocol.connection_lost = lambda e: fut.set_result(e)
        self.cc.send.side_effect = ConnectionError()
        self.handle.write(b"data")
        run_coroutine(fut)
        self.assertIs(fut.result(), self.cc.send.side_effect)
        self.assertFalse(self.s._sessions)

        (_, (iq1,), _), = self.cc.send.mock_calls
        self.assertEqual(iq1.type_, aioxmpp.IQType.SET)
        self.assertIsInstance(iq1.payload, ibb_xso.Data)

    def test_remote_abort_during_close(self):
        fut = asyncio.Future()
        self.protocol.connection_lost = lambda e: fut.set_result(e)
        self.cc.send.side_effect = aioxmpp.errors.XMPPCancelError(
            aioxmpp.errors.ErrorCondition.ITEM_NOT_FOUND
        )
        self.handle.close()
        run_coroutine(fut)
        self.assertIs(fut.result(), self.cc.send.side_effect)

    def test_close(self):
        fut = asyncio.Future()
        self.protocol.connection_lost = lambda e: fut.set_result(None)
        self.handle.close()
        run_coroutine(fut)
        (_, (iq,), _), = self.cc.send.mock_calls
        self.assertEqual(iq.to, TEST_JID1)
        self.assertIsInstance(iq.payload, ibb_xso.Close)
        self.assertEqual(iq.payload.sid, self.handle.get_extra_info("sid"))
        self.assertFalse(self.s._sessions)

    def test_remote_close(self):
        fut = asyncio.Future()
        self.protocol.connection_lost = lambda e: fut.set_result(None)

        close = ibb_xso.Close()
        close.sid = self.handle.get_extra_info("sid")
        stanza = aioxmpp.IQ(
            aioxmpp.IQType.SET,
            from_=TEST_JID1,
            to=TEST_FROM,
            payload=close
        )
        run_coroutine(self.s._handle_close_request(stanza))
        run_coroutine(fut)
        self.assertFalse(self.s._sessions)

    def test_fill_buffer(self):
        pause_fut = asyncio.Future()
        resume_fut = asyncio.Future()
        # hack the block size
        self.handle._block_size = 5
        self.handle.set_write_buffer_limits(20, 10)
        self.protocol.pause_writing = lambda: pause_fut.set_result(True)
        self.protocol.resume_writing = lambda: resume_fut.set_result(True)
        self.handle.write(b" " * 21)
        run_coroutine(pause_fut)
        run_coroutine(resume_fut)
        self.assertLess(len(self.handle._write_buffer), 10)
        self.assertGreater(len(self.handle._write_buffer), 0)

class TestIBBService_OpenConnectionMessage(unittest.TestCase):

    def setUp(self):
        self.cc = make_connected_client()
        self.cc.local_jid = TEST_FROM
        self.s = ibb.IBBService(
            self.cc,
        )
        protocol_factory = unittest.mock.Mock()
        self.handle, self.protocol = run_coroutine(
            self.s.open_session(protocol_factory, TEST_JID1,
                                stanza_type=ibb_xso.IBBStanzaType.MESSAGE)
        )
        self.cc.send.mock_calls.clear()

    def tearDown(self):
        # ensure clean-up
        self.s._on_stream_destroyed()
        del self.cc
        del self.s

    def test_leave_non_protocol_messages_intact(self):
        stanza = aioxmpp.Message(
            aioxmpp.MessageType.NORMAL,
            from_=TEST_JID1,
            to=TEST_FROM,
        )
        self.assertIs(self.s._handle_message(stanza), stanza)

    def test_send(self):

        for i in range(5):
            fut = asyncio.Future()

            async def patched_send(stanza):
                fut.set_result(None)
                patched_send.argument = stanza

            self.cc.send = patched_send
            self.handle.write(b"some data")
            run_coroutine(fut)
            msg = patched_send.argument
            self.assertEqual(msg.to, TEST_JID1)
            self.assertIsInstance(msg.xep0047_data, ibb_xso.Data)
            self.assertEqual(msg.xep0047_data.sid,
                             self.handle.get_extra_info("sid"))
            self.assertEqual(msg.xep0047_data.seq, i)
            self.assertEqual(msg.xep0047_data.content, b"some data")

    # def test_send_long(self):
    #     run_coroutine(self.handle.send(b" " * 4097))
    #     self.assertEqual(
    #         len(self.cc.send.mock_calls),
    #         2
    #     )

    def test_receive(self):

        proto = TestProtocol()
        self.handle.set_protocol(proto)
        total_text = b""
        for i in range(5):
            text = "data{}".format(i).encode("us-ascii")
            stanza = aioxmpp.Message(
                aioxmpp.MessageType.NORMAL,
                from_=TEST_JID1,
                to=TEST_FROM,
            )
            stanza.xep0047_data = ibb_xso.Data(
                self.handle.get_extra_info("sid"),
                i,
                text
            )

            total_text += text
            self.s._handle_message(stanza)

        self.assertEqual(
            proto.data, total_text
        )

    def test_receive_invalid_session(self):
        proto = TestProtocol()
        self.handle.set_protocol(proto)

        stanza = aioxmpp.Message(
            aioxmpp.MessageType.NORMAL,
            from_=TEST_JID1,
            to=TEST_FROM,
        )
        stanza.xep0047_data = ibb_xso.Data(
            "fnord",
            0,
            b"data",
        )

        self.s._handle_message(stanza)
        self.assertEqual(proto.data, b"")

    def test_receive_invalid_seq(self):
        proto = TestProtocol()
        self.handle.set_protocol(proto)

        stanza = aioxmpp.Message(
            aioxmpp.MessageType.NORMAL,
            from_=TEST_JID1,
            to=TEST_FROM,
        )

        stanza.xep0047_data = ibb_xso.Data(
            self.handle.get_extra_info("sid"),
            1,
            b"data",
        )

        self.s._handle_message(stanza)
        self.assertEqual(proto.data, b"")


class TestIBBTransport(unittest.TestCase):

    def setUp(self):
        self.cc = make_connected_client()
        self.cc.local_jid = TEST_FROM
        self.s = ibb.IBBService(
            self.cc,
        )
        protocol_factory = unittest.mock.Mock()
        self.handle, self.protocol = run_coroutine(
            self.s.open_session(protocol_factory, TEST_JID1)
        )
        self.cc.send.mock_calls.clear()

    def tearDown(self):
        # ensure clean-up
        self.s._on_stream_destroyed()
        del self.cc
        del self.s

    def test_set_write_buffer_limits(self):
        self.handle.set_write_buffer_limits(10000, 100)
        self.assertEqual(
            self.handle.get_write_buffer_limits(),
            (100, 10000)
        )

    def test_set_write_buffer_limits_only_high(self):
        low_before, high_before = self.handle.get_write_buffer_limits()
        self.handle.set_write_buffer_limits(high_before*2)
        self.assertEqual(
            self.handle.get_write_buffer_limits(),
            (low_before, high_before*2)
        )

    def test_set_write_buffer_limits_reject_negative(self):
        with self.assertRaises(ValueError):
            self.handle.set_write_buffer_limits(-10, 0)

        with self.assertRaises(ValueError):
            self.handle.set_write_buffer_limits(0, -10)

    def test_set_write_buffer_limits_set_to_zeroe(self):
        self.handle.set_write_buffer_limits(0)
        self.assertEqual(
            self.handle.get_write_buffer_limits(),
            (0, 0)
        )

    def test_set_write_buffer_limits_defaults(self):
        low_before, high_before = self.handle.get_write_buffer_limits()
        self.handle.set_write_buffer_limits(10000, 100)
        self.handle.set_write_buffer_limits()
        self.assertEqual(
            self.handle.get_write_buffer_limits(),
            (low_before, high_before)
        )

    def test_get_write_buffer_size(self):
        self.handle.write(b" "*10)
        self.assertEqual(self.handle.get_write_buffer_size(), 10)

    def test_get_protocol(self):
        self.assertIs(self.handle.get_protocol(), self.protocol)

    def test_pause_and_resume_reading(self):
        self.handle.pause_reading()
        self.handle._data_received(b"foo")
        self.handle._data_received(b"bar")
        self.assertSequenceEqual(
            self.protocol.data_received.mock_calls,
            []
        )
        self.handle.resume_reading()
        self.assertSequenceEqual(
            self.protocol.data_received.mock_calls,
            [unittest.mock.call(b"foobar")]
        )