Debian Codegraph @

tests/test-wireproto-clientreactor.py

raw
1 import sys
2 import unittest
3 import zlib
4
5 from mercurial import (
6 error,
7 ui as uimod,
8 wireprotoframing as framing,
9 )
10 from mercurial.utils import cborutil
11
12 try:
13 from mercurial import zstd
14
15 zstd.__version__
16 except ImportError:
17 zstd = None
18
19 ffs = framing.makeframefromhumanstring
20
21 globalui = uimod.ui()
22
23
24 def sendframe(reactor, frame):
25 """Send a frame bytearray to a reactor."""
26 header = framing.parseheader(frame)
27 payload = frame[framing.FRAME_HEADER_SIZE :]
28 assert len(payload) == header.length
29
30 return reactor.onframerecv(
31 framing.frame(
32 header.requestid,
33 header.streamid,
34 header.streamflags,
35 header.typeid,
36 header.flags,
37 payload,
38 )
39 )
40
41
42 class SingleSendTests(unittest.TestCase):
43 """A reactor that can only send once rejects subsequent sends."""
44
45 if not getattr(unittest.TestCase, 'assertRaisesRegex', False):
46 # Python 3.7 deprecates the regex*p* version, but 2.7 lacks
47 # the regex version.
48 assertRaisesRegex = ( # camelcase-required
49 unittest.TestCase.assertRaisesRegexp
50 )
51
52 def testbasic(self):
53 reactor = framing.clientreactor(
54 globalui, hasmultiplesend=False, buffersends=True
55 )
56
57 request, action, meta = reactor.callcommand(b'foo', {})
58 self.assertEqual(request.state, b'pending')
59 self.assertEqual(action, b'noop')
60
61 action, meta = reactor.flushcommands()
62 self.assertEqual(action, b'sendframes')
63
64 for frame in meta[b'framegen']:
65 self.assertEqual(request.state, b'sending')
66
67 self.assertEqual(request.state, b'sent')
68
69 with self.assertRaisesRegex(
70 error.ProgrammingError, 'cannot issue new commands'
71 ):
72 reactor.callcommand(b'foo', {})
73
74 with self.assertRaisesRegex(
75 error.ProgrammingError, 'cannot issue new commands'
76 ):
77 reactor.callcommand(b'foo', {})
78
79
80 class NoBufferTests(unittest.TestCase):
81 """A reactor without send buffering sends requests immediately."""
82
83 def testbasic(self):
84 reactor = framing.clientreactor(
85 globalui, hasmultiplesend=True, buffersends=False
86 )
87
88 request, action, meta = reactor.callcommand(b'command1', {})
89 self.assertEqual(request.requestid, 1)
90 self.assertEqual(action, b'sendframes')
91
92 self.assertEqual(request.state, b'pending')
93
94 for frame in meta[b'framegen']:
95 self.assertEqual(request.state, b'sending')
96
97 self.assertEqual(request.state, b'sent')
98
99 action, meta = reactor.flushcommands()
100 self.assertEqual(action, b'noop')
101
102 # And we can send another command.
103 request, action, meta = reactor.callcommand(b'command2', {})
104 self.assertEqual(request.requestid, 3)
105 self.assertEqual(action, b'sendframes')
106
107 for frame in meta[b'framegen']:
108 self.assertEqual(request.state, b'sending')
109
110 self.assertEqual(request.state, b'sent')
111
112
113 class BadFrameRecvTests(unittest.TestCase):
114 if not getattr(unittest.TestCase, 'assertRaisesRegex', False):
115 # Python 3.7 deprecates the regex*p* version, but 2.7 lacks
116 # the regex version.
117 assertRaisesRegex = ( # camelcase-required
118 unittest.TestCase.assertRaisesRegexp
119 )
120
121 def testoddstream(self):
122 reactor = framing.clientreactor(globalui)
123
124 action, meta = sendframe(reactor, ffs(b'1 1 0 1 0 foo'))
125 self.assertEqual(action, b'error')
126 self.assertEqual(
127 meta[b'message'], b'received frame with odd numbered stream ID: 1'
128 )
129
130 def testunknownstream(self):
131 reactor = framing.clientreactor(globalui)
132
133 action, meta = sendframe(reactor, ffs(b'1 0 0 1 0 foo'))
134 self.assertEqual(action, b'error')
135 self.assertEqual(
136 meta[b'message'],
137 b'received frame on unknown stream without beginning '
138 b'of stream flag set',
139 )
140
141 def testunhandledframetype(self):
142 reactor = framing.clientreactor(globalui, buffersends=False)
143
144 request, action, meta = reactor.callcommand(b'foo', {})
145 for frame in meta[b'framegen']:
146 pass
147
148 with self.assertRaisesRegex(
149 error.ProgrammingError, 'unhandled frame type'
150 ):
151 sendframe(reactor, ffs(b'1 0 stream-begin text-output 0 foo'))
152
153
154 class StreamTests(unittest.TestCase):
155 def testmultipleresponseframes(self):
156 reactor = framing.clientreactor(globalui, buffersends=False)
157
158 request, action, meta = reactor.callcommand(b'foo', {})
159
160 self.assertEqual(action, b'sendframes')
161 for f in meta[b'framegen']:
162 pass
163
164 action, meta = sendframe(
165 reactor,
166 ffs(
167 b'%d 0 stream-begin command-response 0 foo' % request.requestid
168 ),
169 )
170 self.assertEqual(action, b'responsedata')
171
172 action, meta = sendframe(
173 reactor, ffs(b'%d 0 0 command-response eos bar' % request.requestid)
174 )
175 self.assertEqual(action, b'responsedata')
176
177
178 class RedirectTests(unittest.TestCase):
179 def testredirect(self):
180 reactor = framing.clientreactor(globalui, buffersends=False)
181
182 redirect = {
183 b'targets': [b'a', b'b'],
184 b'hashes': [b'sha256'],
185 }
186
187 request, action, meta = reactor.callcommand(
188 b'foo', {}, redirect=redirect
189 )
190
191 self.assertEqual(action, b'sendframes')
192
193 frames = list(meta[b'framegen'])
194 self.assertEqual(len(frames), 1)
195
196 self.assertEqual(
197 frames[0],
198 ffs(
199 b'1 1 stream-begin command-request new '
200 b"cbor:{b'name': b'foo', "
201 b"b'redirect': {b'targets': [b'a', b'b'], "
202 b"b'hashes': [b'sha256']}}"
203 ),
204 )
205
206
207 class StreamSettingsTests(unittest.TestCase):
208 def testnoflags(self):
209 reactor = framing.clientreactor(globalui, buffersends=False)
210
211 request, action, meta = reactor.callcommand(b'foo', {})
212 for f in meta[b'framegen']:
213 pass
214
215 action, meta = sendframe(
216 reactor, ffs(b'1 2 stream-begin stream-settings 0 ')
217 )
218
219 self.assertEqual(action, b'error')
220 self.assertEqual(
221 meta,
222 {
223 b'message': b'stream encoding settings frame must have '
224 b'continuation or end of stream flag set',
225 },
226 )
227
228 def testconflictflags(self):
229 reactor = framing.clientreactor(globalui, buffersends=False)
230
231 request, action, meta = reactor.callcommand(b'foo', {})
232 for f in meta[b'framegen']:
233 pass
234
235 action, meta = sendframe(
236 reactor, ffs(b'1 2 stream-begin stream-settings continuation|eos ')
237 )
238
239 self.assertEqual(action, b'error')
240 self.assertEqual(
241 meta,
242 {
243 b'message': b'stream encoding settings frame cannot have both '
244 b'continuation and end of stream flags set',
245 },
246 )
247
248 def testemptypayload(self):
249 reactor = framing.clientreactor(globalui, buffersends=False)
250
251 request, action, meta = reactor.callcommand(b'foo', {})
252 for f in meta[b'framegen']:
253 pass
254
255 action, meta = sendframe(
256 reactor, ffs(b'1 2 stream-begin stream-settings eos ')
257 )
258
259 self.assertEqual(action, b'error')
260 self.assertEqual(
261 meta,
262 {
263 b'message': b'stream encoding settings frame did not contain '
264 b'CBOR data'
265 },
266 )
267
268 def testbadcbor(self):
269 reactor = framing.clientreactor(globalui, buffersends=False)
270
271 request, action, meta = reactor.callcommand(b'foo', {})
272 for f in meta[b'framegen']:
273 pass
274
275 action, meta = sendframe(
276 reactor, ffs(b'1 2 stream-begin stream-settings eos badvalue')
277 )
278
279 self.assertEqual(action, b'error')
280
281 def testsingleobject(self):
282 reactor = framing.clientreactor(globalui, buffersends=False)
283
284 request, action, meta = reactor.callcommand(b'foo', {})
285 for f in meta[b'framegen']:
286 pass
287
288 action, meta = sendframe(
289 reactor,
290 ffs(b'1 2 stream-begin stream-settings eos cbor:b"identity"'),
291 )
292
293 self.assertEqual(action, b'noop')
294 self.assertEqual(meta, {})
295
296 def testmultipleobjects(self):
297 reactor = framing.clientreactor(globalui, buffersends=False)
298
299 request, action, meta = reactor.callcommand(b'foo', {})
300 for f in meta[b'framegen']:
301 pass
302
303 data = b''.join(
304 [
305 b''.join(cborutil.streamencode(b'identity')),
306 b''.join(cborutil.streamencode({b'foo', b'bar'})),
307 ]
308 )
309
310 action, meta = sendframe(
311 reactor, ffs(b'1 2 stream-begin stream-settings eos %s' % data)
312 )
313
314 self.assertEqual(action, b'error')
315 self.assertEqual(
316 meta,
317 {
318 b'message': b'error setting stream decoder: identity decoder '
319 b'received unexpected additional values',
320 },
321 )
322
323 def testmultipleframes(self):
324 reactor = framing.clientreactor(globalui, buffersends=False)
325
326 request, action, meta = reactor.callcommand(b'foo', {})
327 for f in meta[b'framegen']:
328 pass
329
330 data = b''.join(cborutil.streamencode(b'identity'))
331
332 action, meta = sendframe(
333 reactor,
334 ffs(
335 b'1 2 stream-begin stream-settings continuation %s' % data[0:3]
336 ),
337 )
338
339 self.assertEqual(action, b'noop')
340 self.assertEqual(meta, {})
341
342 action, meta = sendframe(
343 reactor, ffs(b'1 2 0 stream-settings eos %s' % data[3:])
344 )
345
346 self.assertEqual(action, b'noop')
347 self.assertEqual(meta, {})
348
349 def testinvalidencoder(self):
350 reactor = framing.clientreactor(globalui, buffersends=False)
351
352 request, action, meta = reactor.callcommand(b'foo', {})
353 for f in meta[b'framegen']:
354 pass
355
356 action, meta = sendframe(
357 reactor,
358 ffs(b'1 2 stream-begin stream-settings eos cbor:b"badvalue"'),
359 )
360
361 self.assertEqual(action, b'error')
362 self.assertEqual(
363 meta,
364 {
365 b'message': b'error setting stream decoder: unknown stream '
366 b'decoder: badvalue',
367 },
368 )
369
370 def testzlibencoding(self):
371 reactor = framing.clientreactor(globalui, buffersends=False)
372
373 request, action, meta = reactor.callcommand(b'foo', {})
374 for f in meta[b'framegen']:
375 pass
376
377 action, meta = sendframe(
378 reactor,
379 ffs(
380 b'%d 2 stream-begin stream-settings eos cbor:b"zlib"'
381 % request.requestid
382 ),
383 )
384
385 self.assertEqual(action, b'noop')
386 self.assertEqual(meta, {})
387
388 result = {
389 b'status': b'ok',
390 }
391 encoded = b''.join(cborutil.streamencode(result))
392
393 compressed = zlib.compress(encoded)
394 self.assertEqual(zlib.decompress(compressed), encoded)
395
396 action, meta = sendframe(
397 reactor,
398 ffs(
399 b'%d 2 encoded command-response eos %s'
400 % (request.requestid, compressed)
401 ),
402 )
403
404 self.assertEqual(action, b'responsedata')
405 self.assertEqual(meta[b'data'], encoded)
406
407 def testzlibencodingsinglebyteframes(self):
408 reactor = framing.clientreactor(globalui, buffersends=False)
409
410 request, action, meta = reactor.callcommand(b'foo', {})
411 for f in meta[b'framegen']:
412 pass
413
414 action, meta = sendframe(
415 reactor,
416 ffs(
417 b'%d 2 stream-begin stream-settings eos cbor:b"zlib"'
418 % request.requestid
419 ),
420 )
421
422 self.assertEqual(action, b'noop')
423 self.assertEqual(meta, {})
424
425 result = {
426 b'status': b'ok',
427 }
428 encoded = b''.join(cborutil.streamencode(result))
429
430 compressed = zlib.compress(encoded)
431 self.assertEqual(zlib.decompress(compressed), encoded)
432
433 chunks = []
434
435 for i in range(len(compressed)):
436 char = compressed[i : i + 1]
437 if char == b'\\':
438 char = b'\\\\'
439 action, meta = sendframe(
440 reactor,
441 ffs(
442 b'%d 2 encoded command-response continuation %s'
443 % (request.requestid, char)
444 ),
445 )
446
447 self.assertEqual(action, b'responsedata')
448 chunks.append(meta[b'data'])
449 self.assertTrue(meta[b'expectmore'])
450 self.assertFalse(meta[b'eos'])
451
452 # zlib will have the full data decoded at this point, even though
453 # we haven't flushed.
454 self.assertEqual(b''.join(chunks), encoded)
455
456 # End the stream for good measure.
457 action, meta = sendframe(
458 reactor,
459 ffs(b'%d 2 stream-end command-response eos ' % request.requestid),
460 )
461
462 self.assertEqual(action, b'responsedata')
463 self.assertEqual(meta[b'data'], b'')
464 self.assertFalse(meta[b'expectmore'])
465 self.assertTrue(meta[b'eos'])
466
467 def testzlibmultipleresponses(self):
468 # We feed in zlib compressed data on the same stream but belonging to
469 # 2 different requests. This tests our flushing behavior.
470 reactor = framing.clientreactor(
471 globalui, buffersends=False, hasmultiplesend=True
472 )
473
474 request1, action, meta = reactor.callcommand(b'foo', {})
475 for f in meta[b'framegen']:
476 pass
477
478 request2, action, meta = reactor.callcommand(b'foo', {})
479 for f in meta[b'framegen']:
480 pass
481
482 outstream = framing.outputstream(2)
483 outstream.setencoder(globalui, b'zlib')
484
485 response1 = b''.join(
486 cborutil.streamencode(
487 {
488 b'status': b'ok',
489 b'extra': b'response1' * 10,
490 }
491 )
492 )
493
494 response2 = b''.join(
495 cborutil.streamencode(
496 {
497 b'status': b'error',
498 b'extra': b'response2' * 10,
499 }
500 )
501 )
502
503 action, meta = sendframe(
504 reactor,
505 ffs(
506 b'%d 2 stream-begin stream-settings eos cbor:b"zlib"'
507 % request1.requestid
508 ),
509 )
510
511 self.assertEqual(action, b'noop')
512 self.assertEqual(meta, {})
513
514 # Feeding partial data in won't get anything useful out.
515 action, meta = sendframe(
516 reactor,
517 ffs(
518 b'%d 2 encoded command-response continuation %s'
519 % (request1.requestid, outstream.encode(response1))
520 ),
521 )
522 self.assertEqual(action, b'responsedata')
523 self.assertEqual(meta[b'data'], b'')
524
525 # But flushing data at both ends will get our original data.
526 action, meta = sendframe(
527 reactor,
528 ffs(
529 b'%d 2 encoded command-response eos %s'
530 % (request1.requestid, outstream.flush())
531 ),
532 )
533 self.assertEqual(action, b'responsedata')
534 self.assertEqual(meta[b'data'], response1)
535
536 # We should be able to reuse the compressor/decompressor for the
537 # 2nd response.
538 action, meta = sendframe(
539 reactor,
540 ffs(
541 b'%d 2 encoded command-response continuation %s'
542 % (request2.requestid, outstream.encode(response2))
543 ),
544 )
545 self.assertEqual(action, b'responsedata')
546 self.assertEqual(meta[b'data'], b'')
547
548 action, meta = sendframe(
549 reactor,
550 ffs(
551 b'%d 2 encoded command-response eos %s'
552 % (request2.requestid, outstream.flush())
553 ),
554 )
555 self.assertEqual(action, b'responsedata')
556 self.assertEqual(meta[b'data'], response2)
557
558 @unittest.skipUnless(zstd, 'zstd not available')
559 def testzstd8mbencoding(self):
560 reactor = framing.clientreactor(globalui, buffersends=False)
561
562 request, action, meta = reactor.callcommand(b'foo', {})
563 for f in meta[b'framegen']:
564 pass
565
566 action, meta = sendframe(
567 reactor,
568 ffs(
569 b'%d 2 stream-begin stream-settings eos cbor:b"zstd-8mb"'
570 % request.requestid
571 ),
572 )
573
574 self.assertEqual(action, b'noop')
575 self.assertEqual(meta, {})
576
577 result = {
578 b'status': b'ok',
579 }
580 encoded = b''.join(cborutil.streamencode(result))
581
582 encoder = framing.zstd8mbencoder(globalui)
583 compressed = encoder.encode(encoded) + encoder.finish()
584 self.assertEqual(
585 zstd.ZstdDecompressor().decompress(
586 compressed, max_output_size=len(encoded)
587 ),
588 encoded,
589 )
590
591 action, meta = sendframe(
592 reactor,
593 ffs(
594 b'%d 2 encoded command-response eos %s'
595 % (request.requestid, compressed)
596 ),
597 )
598
599 self.assertEqual(action, b'responsedata')
600 self.assertEqual(meta[b'data'], encoded)
601
602 @unittest.skipUnless(zstd, 'zstd not available')
603 def testzstd8mbencodingsinglebyteframes(self):
604 reactor = framing.clientreactor(globalui, buffersends=False)
605
606 request, action, meta = reactor.callcommand(b'foo', {})
607 for f in meta[b'framegen']:
608 pass
609
610 action, meta = sendframe(
611 reactor,
612 ffs(
613 b'%d 2 stream-begin stream-settings eos cbor:b"zstd-8mb"'
614 % request.requestid
615 ),
616 )
617
618 self.assertEqual(action, b'noop')
619 self.assertEqual(meta, {})
620
621 result = {
622 b'status': b'ok',
623 }
624 encoded = b''.join(cborutil.streamencode(result))
625
626 compressed = zstd.ZstdCompressor().compress(encoded)
627 self.assertEqual(
628 zstd.ZstdDecompressor().decompress(compressed), encoded
629 )
630
631 chunks = []
632
633 for i in range(len(compressed)):
634 char = compressed[i : i + 1]
635 if char == b'\\':
636 char = b'\\\\'
637 action, meta = sendframe(
638 reactor,
639 ffs(
640 b'%d 2 encoded command-response continuation %s'
641 % (request.requestid, char)
642 ),
643 )
644
645 self.assertEqual(action, b'responsedata')
646 chunks.append(meta[b'data'])
647 self.assertTrue(meta[b'expectmore'])
648 self.assertFalse(meta[b'eos'])
649
650 # zstd decompressor will flush at frame boundaries.
651 self.assertEqual(b''.join(chunks), encoded)
652
653 # End the stream for good measure.
654 action, meta = sendframe(
655 reactor,
656 ffs(b'%d 2 stream-end command-response eos ' % request.requestid),
657 )
658
659 self.assertEqual(action, b'responsedata')
660 self.assertEqual(meta[b'data'], b'')
661 self.assertFalse(meta[b'expectmore'])
662 self.assertTrue(meta[b'eos'])
663
664 @unittest.skipUnless(zstd, 'zstd not available')
665 def testzstd8mbmultipleresponses(self):
666 # We feed in zstd compressed data on the same stream but belonging to
667 # 2 different requests. This tests our flushing behavior.
668 reactor = framing.clientreactor(
669 globalui, buffersends=False, hasmultiplesend=True
670 )
671
672 request1, action, meta = reactor.callcommand(b'foo', {})
673 for f in meta[b'framegen']:
674 pass
675
676 request2, action, meta = reactor.callcommand(b'foo', {})
677 for f in meta[b'framegen']:
678 pass
679
680 outstream = framing.outputstream(2)
681 outstream.setencoder(globalui, b'zstd-8mb')
682
683 response1 = b''.join(
684 cborutil.streamencode(
685 {
686 b'status': b'ok',
687 b'extra': b'response1' * 10,
688 }
689 )
690 )
691
692 response2 = b''.join(
693 cborutil.streamencode(
694 {
695 b'status': b'error',
696 b'extra': b'response2' * 10,
697 }
698 )
699 )
700
701 action, meta = sendframe(
702 reactor,
703 ffs(
704 b'%d 2 stream-begin stream-settings eos cbor:b"zstd-8mb"'
705 % request1.requestid
706 ),
707 )
708
709 self.assertEqual(action, b'noop')
710 self.assertEqual(meta, {})
711
712 # Feeding partial data in won't get anything useful out.
713 action, meta = sendframe(
714 reactor,
715 ffs(
716 b'%d 2 encoded command-response continuation %s'
717 % (request1.requestid, outstream.encode(response1))
718 ),
719 )
720 self.assertEqual(action, b'responsedata')
721 self.assertEqual(meta[b'data'], b'')
722
723 # But flushing data at both ends will get our original data.
724 action, meta = sendframe(
725 reactor,
726 ffs(
727 b'%d 2 encoded command-response eos %s'
728 % (request1.requestid, outstream.flush())
729 ),
730 )
731 self.assertEqual(action, b'responsedata')
732 self.assertEqual(meta[b'data'], response1)
733
734 # We should be able to reuse the compressor/decompressor for the
735 # 2nd response.
736 action, meta = sendframe(
737 reactor,
738 ffs(
739 b'%d 2 encoded command-response continuation %s'
740 % (request2.requestid, outstream.encode(response2))
741 ),
742 )
743 self.assertEqual(action, b'responsedata')
744 self.assertEqual(meta[b'data'], b'')
745
746 action, meta = sendframe(
747 reactor,
748 ffs(
749 b'%d 2 encoded command-response eos %s'
750 % (request2.requestid, outstream.flush())
751 ),
752 )
753 self.assertEqual(action, b'responsedata')
754 self.assertEqual(meta[b'data'], response2)
755
756
757 if __name__ == '__main__':
758 if (3, 6, 0) <= sys.version_info < (3, 6, 4):
759 # Python 3.6.0 through 3.6.3 inclusive shipped with
760 # https://bugs.python.org/issue31825 and we can't run these
761 # tests on those specific versions of Python. Sigh.
762 sys.exit(80)
763 import silenttestrunner
764
765 silenttestrunner.main(__name__)