-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathtest_basic_logic.py
1555 lines (1293 loc) · 52.3 KB
/
test_basic_logic.py
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
test_basic_logic
~~~~~~~~~~~~~~~~
Test the basic logic of the h2 state machines.
"""
import random
import sys
import hyperframe
import pytest
import h2.config
import h2.connection
import h2.errors
import h2.events
import h2.exceptions
import h2.frame_buffer
import h2.settings
import helpers
IS_PYTHON3 = sys.version_info >= (3, 0)
class TestBasicClient(object):
"""
Basic client-side tests.
"""
example_request_headers = [
(u':authority', u'example.com'),
(u':path', u'/'),
(u':scheme', u'https'),
(u':method', u'GET'),
]
bytes_example_request_headers = [
(b':authority', b'example.com'),
(b':path', b'/'),
(b':scheme', b'https'),
(b':method', b'GET'),
]
example_response_headers = [
(u':status', u'200'),
(u'server', u'fake-serv/0.1.0')
]
bytes_example_response_headers = [
(b':status', b'200'),
(b'server', b'fake-serv/0.1.0')
]
def test_begin_connection(self, frame_factory):
"""
Client connections emit the HTTP/2 preamble.
"""
c = h2.connection.H2Connection()
expected_settings = frame_factory.build_settings_frame(
c.local_settings
)
expected_data = (
b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n' + expected_settings.serialize()
)
events = c.initiate_connection()
assert not events
assert c.data_to_send() == expected_data
def test_deprecated_properties(self):
"""
We can access the deprecated properties.
"""
config = h2.config.H2Configuration(
client_side=False, header_encoding=False
)
c = h2.connection.H2Connection(config=config)
assert c.client_side is False
assert c.header_encoding is False
def test_sending_headers(self):
"""
Single headers frames are correctly encoded.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
# Clear the data, then send headers.
c.clear_outbound_data_buffer()
events = c.send_headers(1, self.example_request_headers)
assert not events
assert c.data_to_send() == (
b'\x00\x00\r\x01\x04\x00\x00\x00\x01'
b'A\x88/\x91\xd3]\x05\\\x87\xa7\x84\x87\x82'
)
def test_sending_data(self):
"""
Single data frames are encoded correctly.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
# Clear the data, then send some data.
c.clear_outbound_data_buffer()
events = c.send_data(1, b'some data')
assert not events
assert (
c.data_to_send() == b'\x00\x00\t\x00\x00\x00\x00\x00\x01some data'
)
def test_closing_stream_sending_data(self, frame_factory):
"""
We can close a stream with a data frame.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
f = frame_factory.build_data_frame(
data=b'some data',
flags=['END_STREAM'],
)
# Clear the data, then send some data.
c.clear_outbound_data_buffer()
events = c.send_data(1, b'some data', end_stream=True)
assert not events
assert c.data_to_send() == f.serialize()
def test_receiving_a_response(self, frame_factory):
"""
When receiving a response, the ResponseReceived event fires.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
# Clear the data
f = frame_factory.build_headers_frame(
self.example_response_headers
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 1
assert event.headers == self.example_response_headers
def test_receiving_a_response_bytes(self, frame_factory):
"""
When receiving a response, the ResponseReceived event fires with bytes
headers if the encoding is set appropriately.
"""
config = h2.config.H2Configuration(header_encoding=False)
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
# Clear the data
f = frame_factory.build_headers_frame(
self.example_response_headers
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 1
assert event.headers == self.bytes_example_response_headers
def test_receiving_a_response_change_encoding(self, frame_factory):
"""
When receiving a response, the ResponseReceived event fires with bytes
headers if the encoding is set appropriately, but if this changes then
the change reflects it.
"""
config = h2.config.H2Configuration(header_encoding=False)
c = h2.connection.H2Connection(config=config)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
f = frame_factory.build_headers_frame(
self.example_response_headers
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 1
assert event.headers == self.bytes_example_response_headers
c.send_headers(3, self.example_request_headers, end_stream=True)
c.header_encoding = 'utf-8'
f = frame_factory.build_headers_frame(
self.example_response_headers,
stream_id=3,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.ResponseReceived)
assert event.stream_id == 3
assert event.headers == self.example_response_headers
def test_end_stream_without_data(self, frame_factory):
"""
Ending a stream without data emits a zero-length DATA frame with
END_STREAM set.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=False)
# Clear the data
c.clear_outbound_data_buffer()
f = frame_factory.build_data_frame(b'', flags=['END_STREAM'])
events = c.end_stream(1)
assert not events
assert c.data_to_send() == f.serialize()
def test_cannot_send_headers_on_lower_stream_id(self):
"""
Once stream ID x has been used, cannot use stream ID y where y < x.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(3, self.example_request_headers, end_stream=False)
with pytest.raises(h2.exceptions.StreamIDTooLowError) as e:
c.send_headers(1, self.example_request_headers, end_stream=True)
assert e.value.stream_id == 1
assert e.value.max_stream_id == 3
def test_receiving_pushed_stream(self, frame_factory):
"""
Pushed streams fire a PushedStreamReceived event, followed by
ResponseReceived when the response headers are received.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=False)
f1 = frame_factory.build_headers_frame(
self.example_response_headers
)
f2 = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers,
flags=['END_HEADERS'],
)
f3 = frame_factory.build_headers_frame(
self.example_response_headers,
stream_id=2,
)
data = b''.join(x.serialize() for x in [f1, f2, f3])
events = c.receive_data(data)
assert len(events) == 3
stream_push_event = events[1]
response_event = events[2]
assert isinstance(stream_push_event, h2.events.PushedStreamReceived)
assert isinstance(response_event, h2.events.ResponseReceived)
assert stream_push_event.pushed_stream_id == 2
assert stream_push_event.parent_stream_id == 1
assert (
stream_push_event.headers == self.example_request_headers
)
assert response_event.stream_id == 2
assert response_event.headers == self.example_response_headers
def test_receiving_pushed_stream_bytes(self, frame_factory):
"""
Pushed headers are not decoded if the header encoding is set to False.
"""
c = h2.connection.H2Connection(header_encoding=False)
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=False)
f1 = frame_factory.build_headers_frame(
self.example_response_headers
)
f2 = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers,
flags=['END_HEADERS'],
)
f3 = frame_factory.build_headers_frame(
self.example_response_headers,
stream_id=2,
)
data = b''.join(x.serialize() for x in [f1, f2, f3])
events = c.receive_data(data)
assert len(events) == 3
stream_push_event = events[1]
response_event = events[2]
assert isinstance(stream_push_event, h2.events.PushedStreamReceived)
assert isinstance(response_event, h2.events.ResponseReceived)
assert stream_push_event.pushed_stream_id == 2
assert stream_push_event.parent_stream_id == 1
assert (
stream_push_event.headers == self.bytes_example_request_headers
)
assert response_event.stream_id == 2
assert response_event.headers == self.bytes_example_response_headers
def test_cannot_receive_pushed_stream_when_enable_push_is_0(self,
frame_factory):
"""
If we have set SETTINGS_ENABLE_PUSH to 0, receiving PUSH_PROMISE frames
triggers the connection to be closed.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.local_settings.enable_push = 0
c.send_headers(1, self.example_request_headers, end_stream=False)
f1 = frame_factory.build_settings_frame({}, ack=True)
f2 = frame_factory.build_headers_frame(
self.example_response_headers
)
f3 = frame_factory.build_push_promise_frame(
stream_id=1,
promised_stream_id=2,
headers=self.example_request_headers,
flags=['END_HEADERS'],
)
c.receive_data(f1.serialize())
c.receive_data(f2.serialize())
c.clear_outbound_data_buffer()
with pytest.raises(h2.exceptions.ProtocolError):
c.receive_data(f3.serialize())
expected_frame = frame_factory.build_goaway_frame(
0, h2.errors.ErrorCodes.PROTOCOL_ERROR
)
assert c.data_to_send() == expected_frame.serialize()
def test_receiving_response_no_body(self, frame_factory):
"""
Receiving a response without a body fires two events, ResponseReceived
and StreamEnded.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
f = frame_factory.build_headers_frame(
self.example_response_headers,
flags=['END_STREAM']
)
events = c.receive_data(f.serialize())
assert len(events) == 2
response_event = events[0]
end_stream = events[1]
assert isinstance(response_event, h2.events.ResponseReceived)
assert isinstance(end_stream, h2.events.StreamEnded)
def test_oversize_headers(self):
"""
Sending headers that are oversized generates a stream of CONTINUATION
frames.
"""
all_bytes = [chr(x) for x in range(0, 256)]
if IS_PYTHON3:
all_bytes = [x.encode('latin1') for x in all_bytes]
large_binary_string = b''.join(
random.choice(all_bytes) for _ in range(0, 256)
)
test_headers = [
(':authority', 'example.com'),
('key', large_binary_string)
]
c = h2.connection.H2Connection()
# Greatly shrink the max frame size to force us over.
c.max_outbound_frame_size = 48
c.initiate_connection()
c.send_headers(1, test_headers, end_stream=True)
# Use the frame buffer here, because we don't care about decoding
# the headers. Don't send all the data in because that will force the
# frame buffer to stop caching the CONTINUATION frames, so instead
# send all but one byte.
buffer = h2.frame_buffer.FrameBuffer(server=True)
buffer.max_frame_size = 65535
data = c.data_to_send()
buffer.add_data(data[:-1])
# Drain the buffer, confirming that it only provides a single frame
# (the settings frame)
assert len(list(buffer)) == 1
# Get the cached frames.
frames = buffer._headers_buffer
# Split the frames up.
headers_frame = frames[0]
continuation_frames = frames[1:]
assert isinstance(headers_frame, hyperframe.frame.HeadersFrame)
assert all(
map(
lambda f: isinstance(f, hyperframe.frame.ContinuationFrame),
continuation_frames)
)
assert all(
map(lambda f: len(f.data) <= c.max_outbound_frame_size, frames)
)
assert frames[0].flags == {'END_STREAM'}
buffer.add_data(data[-1:])
headers = list(buffer)[0]
assert isinstance(headers, hyperframe.frame.HeadersFrame)
def test_dict_headers(self):
"""
Sending headers using dict is deprecated but still valid.
"""
# One of the steps in the outbound header validation logic checks
# that we don't send a pseudo-header after we've sent a regular
# header. We can't guarantee that if you send headers as a dict,
# because dicts are unordered.
config = h2.config.H2Configuration(
validate_outbound_headers=False
)
test_headers = {':authority': 'example.com', 'key': 'value'}
c = h2.connection.H2Connection(config=config)
pytest.deprecated_call(c.send_headers, 1, test_headers)
def test_handle_stream_reset(self, frame_factory):
"""
Streams being remotely reset fires a StreamReset event.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
c.clear_outbound_data_buffer()
f = frame_factory.build_rst_stream_frame(
stream_id=1,
error_code=h2.errors.ErrorCodes.STREAM_CLOSED,
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.StreamReset)
assert event.stream_id == 1
assert event.error_code is h2.errors.ErrorCodes.STREAM_CLOSED
assert isinstance(event.error_code, h2.errors.ErrorCodes)
assert event.remote_reset
def test_handle_stream_reset_with_unknown_erorr_code(self, frame_factory):
"""
Streams being remotely reset with unknown error codes behave exactly as
they do with known error codes, but the error code on the event is an
int, instead of being an ErrorCodes.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers, end_stream=True)
c.clear_outbound_data_buffer()
f = frame_factory.build_rst_stream_frame(stream_id=1, error_code=0xFA)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.StreamReset)
assert event.stream_id == 1
assert event.error_code == 250
assert not isinstance(event.error_code, h2.errors.ErrorCodes)
assert event.remote_reset
def test_can_consume_partial_data_from_connection(self):
"""
We can do partial reads from the connection.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
assert len(c.data_to_send(2)) == 2
assert len(c.data_to_send(3)) == 3
assert 0 < len(c.data_to_send(500)) < 500
assert len(c.data_to_send(10)) == 0
assert len(c.data_to_send()) == 0
def test_we_can_update_settings(self, frame_factory):
"""
Updating the settings emits a SETTINGS frame.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.clear_outbound_data_buffer()
new_settings = {
h2.settings.HEADER_TABLE_SIZE: 52,
h2.settings.ENABLE_PUSH: 0,
}
events = c.update_settings(new_settings)
assert not events
f = frame_factory.build_settings_frame(new_settings)
assert c.data_to_send() == f.serialize()
def test_settings_get_acked_correctly(self, frame_factory):
"""
When settings changes are ACKed, they contain the changed settings.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
new_settings = {
h2.settings.HEADER_TABLE_SIZE: 52,
h2.settings.ENABLE_PUSH: 0,
}
c.update_settings(new_settings)
f = frame_factory.build_settings_frame({}, ack=True)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.SettingsAcknowledged)
assert len(event.changed_settings) == len(new_settings)
for setting, value in new_settings.items():
assert event.changed_settings[setting].new_value == value
def test_cannot_create_new_outbound_stream_over_limit(self, frame_factory):
"""
When the number of outbound streams exceeds the remote peer's
MAX_CONCURRENT_STREAMS setting, attempting to open new streams fails.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
f = frame_factory.build_settings_frame(
{h2.settings.MAX_CONCURRENT_STREAMS: 1}
)
c.receive_data(f.serialize())[0]
c.send_headers(1, self.example_request_headers)
with pytest.raises(h2.exceptions.TooManyStreamsError):
c.send_headers(3, self.example_request_headers)
def test_can_receive_trailers(self, frame_factory):
"""
When two HEADERS blocks are received in the same stream from a
server, the second set are trailers.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
f = frame_factory.build_headers_frame(self.example_response_headers)
c.receive_data(f.serialize())
# Send in trailers.
trailers = [('content-length', '0')]
f = frame_factory.build_headers_frame(
trailers,
flags=['END_STREAM'],
)
events = c.receive_data(f.serialize())
assert len(events) == 2
event = events[0]
assert isinstance(event, h2.events.TrailersReceived)
assert event.headers == trailers
assert event.stream_id == 1
def test_reject_trailers_not_ending_stream(self, frame_factory):
"""
When trailers are received without the END_STREAM flag being present,
this is a ProtocolError.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.send_headers(1, self.example_request_headers)
f = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(f.serialize())
# Send in trailers.
c.clear_outbound_data_buffer()
trailers = [('content-length', '0')]
f = frame_factory.build_headers_frame(
trailers,
flags=[],
)
with pytest.raises(h2.exceptions.ProtocolError):
c.receive_data(f.serialize())
expected_frame = frame_factory.build_goaway_frame(
last_stream_id=0, error_code=h2.errors.ErrorCodes.PROTOCOL_ERROR,
)
assert c.data_to_send() == expected_frame.serialize()
def test_can_send_trailers(self, frame_factory):
"""
When a second set of headers are sent, they are properly trailers.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
c.clear_outbound_data_buffer()
c.send_headers(1, self.example_request_headers)
# Now send trailers.
trailers = [('content-length', '0')]
c.send_headers(1, trailers, end_stream=True)
frame_factory.refresh_encoder()
f1 = frame_factory.build_headers_frame(
self.example_request_headers,
)
f2 = frame_factory.build_headers_frame(
trailers,
flags=['END_STREAM'],
)
assert c.data_to_send() == f1.serialize() + f2.serialize()
def test_trailers_must_have_end_stream(self, frame_factory):
"""
A set of trailers must carry the END_STREAM flag.
"""
c = h2.connection.H2Connection()
c.initiate_connection()
# Send headers.
c.send_headers(1, self.example_request_headers)
# Now send trailers.
trailers = [('content-length', '0')]
with pytest.raises(h2.exceptions.ProtocolError):
c.send_headers(1, trailers)
def test_headers_are_lowercase(self, frame_factory):
"""
When headers are sent, they are forced to lower-case.
"""
weird_headers = self.example_request_headers + [
('ChAnGiNg-CaSe', 'AlsoHere'),
('alllowercase', 'alllowercase'),
('ALLCAPS', 'ALLCAPS'),
]
expected_headers = self.example_request_headers + [
('changing-case', 'AlsoHere'),
('alllowercase', 'alllowercase'),
('allcaps', 'ALLCAPS'),
]
c = h2.connection.H2Connection()
c.initiate_connection()
c.clear_outbound_data_buffer()
c.send_headers(1, weird_headers)
expected_frame = frame_factory.build_headers_frame(
headers=expected_headers
)
assert c.data_to_send() == expected_frame.serialize()
class TestBasicServer(object):
"""
Basic server-side tests.
"""
example_request_headers = [
(u':authority', u'example.com'),
(u':path', u'/'),
(u':scheme', u'https'),
(u':method', u'GET'),
]
bytes_example_request_headers = [
(b':authority', b'example.com'),
(b':path', b'/'),
(b':scheme', b'https'),
(b':method', b'GET'),
]
example_response_headers = [
(':status', '200'),
('server', 'hyper-h2/0.1.0')
]
def test_ignores_preamble(self):
"""
The preamble does not cause any events or frames to be written.
"""
c = h2.connection.H2Connection(client_side=False)
preamble = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
events = c.receive_data(preamble)
assert not events
assert not c.data_to_send()
@pytest.mark.parametrize("chunk_size", range(1, 24))
def test_drip_feed_preamble(self, chunk_size):
"""
The preamble can be sent in in less than a single buffer.
"""
c = h2.connection.H2Connection(client_side=False)
preamble = b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
events = []
for i in range(0, len(preamble), chunk_size):
events += c.receive_data(preamble[i:i+chunk_size])
assert not events
assert not c.data_to_send()
def test_initiate_connection_sends_server_preamble(self, frame_factory):
"""
For server-side connections, initiate_connection sends a server
preamble.
"""
c = h2.connection.H2Connection(client_side=False)
expected_settings = frame_factory.build_settings_frame(
c.local_settings
)
expected_data = expected_settings.serialize()
events = c.initiate_connection()
assert not events
assert c.data_to_send() == expected_data
def test_headers_event(self, frame_factory):
"""
When a headers frame is received a RequestReceived event fires.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
data = f.serialize()
events = c.receive_data(data)
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.RequestReceived)
assert event.stream_id == 1
assert event.headers == self.example_request_headers
def test_headers_event_bytes(self, frame_factory):
"""
When a headers frame is received a RequestReceived event fires with
bytes headers if the encoding is set appropriately.
"""
c = h2.connection.H2Connection(
client_side=False, header_encoding=False
)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
data = f.serialize()
events = c.receive_data(data)
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.RequestReceived)
assert event.stream_id == 1
assert event.headers == self.bytes_example_request_headers
def test_data_event(self, frame_factory):
"""
Test that data received on a stream fires a DataReceived event.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f1 = frame_factory.build_headers_frame(
self.example_request_headers, stream_id=3
)
f2 = frame_factory.build_data_frame(
b'some request data',
stream_id=3,
)
data = b''.join(map(lambda f: f.serialize(), [f1, f2]))
events = c.receive_data(data)
assert len(events) == 2
event = events[1]
assert isinstance(event, h2.events.DataReceived)
assert event.stream_id == 3
assert event.data == b'some request data'
assert event.flow_controlled_length == 17
def test_data_event_with_padding(self, frame_factory):
"""
Test that data received on a stream fires a DataReceived event that
accounts for padding.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f1 = frame_factory.build_headers_frame(
self.example_request_headers, stream_id=3
)
f2 = frame_factory.build_data_frame(
b'some request data',
stream_id=3,
padding_len=20
)
data = b''.join(map(lambda f: f.serialize(), [f1, f2]))
events = c.receive_data(data)
assert len(events) == 2
event = events[1]
assert isinstance(event, h2.events.DataReceived)
assert event.stream_id == 3
assert event.data == b'some request data'
assert event.flow_controlled_length == 17 + 20 + 1
def test_receiving_ping_frame(self, frame_factory):
"""
Ping frames should be immediately ACKed.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
ping_data = b'\x01' * 8
sent_frame = frame_factory.build_ping_frame(ping_data)
expected_frame = frame_factory.build_ping_frame(
ping_data, flags=["ACK"]
)
expected_data = expected_frame.serialize()
c.clear_outbound_data_buffer()
events = c.receive_data(sent_frame.serialize())
assert not events
assert c.data_to_send() == expected_data
def test_receiving_settings_frame_event(self, frame_factory):
"""
Settings frames should cause a RemoteSettingsChanged event to fire.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_settings_frame(
settings=helpers.SAMPLE_SETTINGS
)
events = c.receive_data(f.serialize())
assert len(events) == 1
event = events[0]
assert isinstance(event, h2.events.RemoteSettingsChanged)
assert len(event.changed_settings) == len(helpers.SAMPLE_SETTINGS)
def test_acknowledging_settings(self, frame_factory):
"""
Acknowledging settings causes appropriate Settings frame to be emitted.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
received_frame = frame_factory.build_settings_frame(
settings=helpers.SAMPLE_SETTINGS
)
expected_frame = frame_factory.build_settings_frame(
settings={}, ack=True
)
expected_data = expected_frame.serialize()
c.clear_outbound_data_buffer()
events = c.receive_data(received_frame.serialize())
assert len(events) == 1
assert c.data_to_send() == expected_data
def test_close_connection(self, frame_factory):
"""
Closing the connection with no error code emits a GOAWAY frame with
error code 0.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_goaway_frame(last_stream_id=0)
expected_data = f.serialize()
c.clear_outbound_data_buffer()
events = c.close_connection()
assert not events
assert c.data_to_send() == expected_data
@pytest.mark.parametrize("error_code", h2.errors.ErrorCodes)
def test_close_connection_with_error_code(self, frame_factory, error_code):
"""
Closing the connection with an error code emits a GOAWAY frame with
that error code.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_goaway_frame(
error_code=error_code, last_stream_id=0
)
expected_data = f.serialize()
c.clear_outbound_data_buffer()
events = c.close_connection(error_code)
assert not events
assert c.data_to_send() == expected_data
@pytest.mark.parametrize("last_stream_id,output", [
(None, 23),
(0, 0),
(42, 42)
])
def test_close_connection_with_last_stream_id(self, frame_factory,
last_stream_id, output):
"""
Closing the connection with last_stream_id set emits a GOAWAY frame
with that value.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
headers_frame = frame_factory.build_headers_frame(
[(':authority', 'example.com')], stream_id=23)
c.receive_data(headers_frame.serialize())
f = frame_factory.build_goaway_frame(
last_stream_id=output
)
expected_data = f.serialize()
c.clear_outbound_data_buffer()
events = c.close_connection(last_stream_id=last_stream_id)
assert not events
assert c.data_to_send() == expected_data
@pytest.mark.parametrize("additional_data,output", [
(None, b''),
(b'', b''),
(b'foobar', b'foobar')
])
def test_close_connection_with_additional_data(self, frame_factory,
additional_data, output):
"""
Closing the connection with additional debug data emits a GOAWAY frame
with that data attached.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_goaway_frame(
last_stream_id=0, additional_data=output
)
expected_data = f.serialize()
c.clear_outbound_data_buffer()
events = c.close_connection(additional_data=additional_data)
assert not events
assert c.data_to_send() == expected_data
def test_reset_stream(self, frame_factory):
"""
Resetting a stream with no error code emits a RST_STREAM frame with
error code 0.
"""
c = h2.connection.H2Connection(client_side=False)
c.receive_data(frame_factory.preamble())
f = frame_factory.build_headers_frame(self.example_request_headers)
c.receive_data(f.serialize())