This repository was archived by the owner on Jan 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathtest_integration.py
More file actions
571 lines (424 loc) · 16.4 KB
/
Copy pathtest_integration.py
File metadata and controls
571 lines (424 loc) · 16.4 KB
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
# -*- coding: utf-8 -*-
"""
test/integration
~~~~~~~~~~~~~~~~
This file defines integration-type tests for hyper. These are still not fully
hitting the network, so that's alright.
"""
import requests
import threading
import hyper
import hyper.http11.connection
import pytest
from hyper.compat import ssl
from hyper.contrib import HTTP20Adapter
from hyper.packages.hyperframe.frame import (
Frame, SettingsFrame, WindowUpdateFrame, DataFrame, HeadersFrame,
GoAwayFrame,
)
from hyper.packages.hpack.hpack import Encoder
from hyper.packages.hpack.huffman import HuffmanEncoder
from hyper.packages.hpack.huffman_constants import (
REQUEST_CODES, REQUEST_CODES_LENGTH
)
from hyper.http20.exceptions import ConnectionError
from server import SocketLevelTest
# Turn off certificate verification for the tests.
if ssl is not None:
hyper.tls._context = hyper.tls.init_context()
hyper.tls._context.check_hostname = False
hyper.tls._context.verify_mode = ssl.CERT_NONE
# Cover our bases because NPN doesn't yet work on all our test platforms.
hyper.http20.connection.H2_NPN_PROTOCOLS += ['', None]
def decode_frame(frame_data):
f, length = Frame.parse_frame_header(frame_data[:9])
f.parse_body(memoryview(frame_data[9:9 + length]))
assert 9 + length == len(frame_data)
return f
def build_headers_frame(headers, encoder=None):
f = HeadersFrame(1)
e = encoder
if e is None:
e = Encoder()
e.huffman_coder = HuffmanEncoder(REQUEST_CODES, REQUEST_CODES_LENGTH)
f.data = e.encode(headers)
f.flags.add('END_HEADERS')
return f
def receive_preamble(sock):
# Receive the HTTP/2 'preamble'.
sock.recv(65535)
sock.recv(65535)
sock.send(SettingsFrame(0).serialize())
sock.recv(65535)
return
class TestHyperIntegration(SocketLevelTest):
# These are HTTP/2 tests.
h2 = True
def test_connection_string(self):
self.set_up()
# Confirm that we send the connection upgrade string and the initial
# SettingsFrame.
data = []
send_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# We should get two packets: one connection header string, one
# SettingsFrame.
first = sock.recv(65535)
second = sock.recv(65535)
data.append(first)
data.append(second)
# We need to send back a SettingsFrame.
f = SettingsFrame(0)
sock.send(f.serialize())
send_event.wait()
sock.close()
self._start_server(socket_handler)
conn = self.get_connection()
conn.connect()
send_event.set()
assert data[0] == b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'
self.tear_down()
def test_initial_settings(self):
self.set_up()
# Confirm that we send the connection upgrade string and the initial
# SettingsFrame.
data = []
send_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# We should get two packets: one connection header string, one
# SettingsFrame.
first = sock.recv(65535)
second = sock.recv(65535)
data.append(first)
data.append(second)
# We need to send back a SettingsFrame.
f = SettingsFrame(0)
sock.send(f.serialize())
send_event.wait()
sock.close()
self._start_server(socket_handler)
conn = self.get_connection()
conn.connect()
send_event.set()
# Get the second chunk of data and decode it into a frame.
data = data[1]
f = decode_frame(data)
assert isinstance(f, SettingsFrame)
assert f.stream_id == 0
assert f.settings == {
SettingsFrame.ENABLE_PUSH: 0,
}
self.tear_down()
def test_stream_level_window_management(self):
self.set_up()
data = []
send_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# Dispose of the first two packets.
sock.recv(65535)
sock.recv(65535)
# Send a Settings frame that reduces the flow-control window to
# 64 bytes.
f = SettingsFrame(0)
f.settings[SettingsFrame.INITIAL_WINDOW_SIZE] = 64
sock.send(f.serialize())
# Grab three frames, the settings ACK, the initial headers frame,
# and the first data frame.
for x in range(0, 3):
data.append(sock.recv(65535))
# Send a WindowUpdate giving more window room to the stream.
f = WindowUpdateFrame(1)
f.window_increment = 64
sock.send(f.serialize())
# Send one that gives more room to the connection.
f = WindowUpdateFrame(0)
f.window_increment = 64
sock.send(f.serialize())
# Reeive the remaining frame.
data.append(sock.recv(65535))
send_event.set()
# We're done.
sock.close()
self._start_server(socket_handler)
conn = self.get_connection()
conn.putrequest('GET', '/')
conn.endheaders()
# Send the first data chunk. This is 32 bytes.
sd = b'a' * 32
conn.send(sd)
# Send the second one. This should block until the WindowUpdate comes
# in.
sd = sd * 2
conn.send(sd, final=True)
assert send_event.wait(0.3)
# Decode the frames.
frames = [decode_frame(d) for d in data]
# We care about the last two. The first should be a data frame
# containing 32 bytes.
assert (isinstance(frames[-2], DataFrame) and
not isinstance(frames[-2], HeadersFrame))
assert len(frames[-2].data) == 32
# The second should be a data frame containing 64 bytes.
assert isinstance(frames[-1], DataFrame)
assert len(frames[-1].data) == 64
self.tear_down()
def test_connection_context_manager(self):
self.set_up()
data = []
send_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# We should get two packets: one connection header string, one
# SettingsFrame.
first = sock.recv(65535)
second = sock.recv(65535)
data.append(first)
data.append(second)
# We need to send back a SettingsFrame.
f = SettingsFrame(0)
sock.send(f.serialize())
send_event.wait()
sock.recv(65535)
sock.close()
self._start_server(socket_handler)
with self.get_connection() as conn:
conn.connect()
send_event.set()
# Check that we closed the connection.
assert conn._sock == None
self.tear_down()
def test_closed_responses_remove_their_streams_from_conn(self):
self.set_up()
recv_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# We're going to get the two messages for the connection open, then
# a headers frame.
receive_preamble(sock)
# Now, send the headers for the response.
f = build_headers_frame([(':status', '200')])
f.stream_id = 1
sock.send(f.serialize())
# Wait for the message from the main thread.
recv_event.wait()
sock.close()
self._start_server(socket_handler)
conn = self.get_connection()
conn.request('GET', '/')
resp = conn.get_response()
# Close the response.
resp.close()
recv_event.set()
assert not conn.streams
self.tear_down()
def test_receiving_responses_with_no_body(self):
self.set_up()
recv_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# We get two messages for the connection open and then a HEADERS
# frame.
receive_preamble(sock)
# Now, send the headers for the response. This response has no body.
f = build_headers_frame([(':status', '204'), ('content-length', '0')])
f.flags.add('END_STREAM')
f.stream_id = 1
sock.send(f.serialize())
# Wait for the message from the main thread.
recv_event.wait()
sock.close()
self._start_server(socket_handler)
conn = self.get_connection()
conn.request('GET', '/')
resp = conn.get_response()
# Confirm the status code.
assert resp.status == 204
# Confirm that we can read this, but it has no body.
assert resp.read() == b''
assert resp._stream._in_window_manager.document_size == 0
# Awesome, we're done now.
recv_event.set()
self.tear_down()
def test_receiving_trailers(self):
self.set_up()
recv_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
e = Encoder()
e.huffman_coder = HuffmanEncoder(REQUEST_CODES, REQUEST_CODES_LENGTH)
# We get two messages for the connection open and then a HEADERS
# frame.
receive_preamble(sock)
# Now, send the headers for the response. This response has no body.
f = build_headers_frame([(':status', '200'), ('content-length', '0')], e)
f.stream_id = 1
sock.send(f.serialize())
# Also send a data frame.
f = DataFrame(1)
f.data = b'have some data'
sock.send(f.serialize())
# Now, send a headers frame again, containing trailing headers.
f = build_headers_frame([('trailing', 'sure'), (':res', 'no')], e)
f.flags.add('END_STREAM')
f.stream_id = 1
sock.send(f.serialize())
# Wait for the message from the main thread.
recv_event.wait()
sock.close()
self._start_server(socket_handler)
conn = self.get_connection()
conn.request('GET', '/')
resp = conn.get_response()
# Confirm the status code.
assert resp.status == 200
# Confirm that we can read this, but it has no body.
assert resp.read() == b'have some data'
assert resp._stream._in_window_manager.document_size == 0
# Confirm that we got the trailing headers, and that they don't contain
# reserved headers.
assert resp.trailers['trailing'] == [b'sure']
assert resp.trailers.get(':res') is None
assert len(resp.headers) == 1
assert len(resp.trailers) == 1
# Awesome, we're done now.
recv_event.set()
self.tear_down()
def test_clean_shut_down(self):
self.set_up()
recv_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# We should get two packets: one connection header string, one
# SettingsFrame. Rather than respond to the packets, send a GOAWAY
# frame with error code 0 indicating clean shutdown.
first = sock.recv(65535)
second = sock.recv(65535)
# Now, send the shut down.
f = GoAwayFrame(0)
f.error_code = 0
sock.send(f.serialize())
# Wait for the message from the main thread.
recv_event.wait()
sock.close()
self._start_server(socket_handler)
conn = self.get_connection()
conn.connect()
# Confirm the connection is closed.
assert conn._sock is None
# Awesome, we're done now.
recv_event.set()
self.tear_down()
def test_unexpected_shut_down(self):
self.set_up()
recv_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# We should get two packets: one connection header string, one
# SettingsFrame. Rather than respond to the packets, send a GOAWAY
# frame with error code 0 indicating clean shutdown.
first = sock.recv(65535)
second = sock.recv(65535)
# Now, send the shut down.
f = GoAwayFrame(0)
f.error_code = 1
sock.send(f.serialize())
# Wait for the message from the main thread.
sock.close()
recv_event.wait()
self._start_server(socket_handler)
conn = self.get_connection()
with pytest.raises(ConnectionError):
conn.connect()
# Confirm the connection is closed.
assert conn._sock is None
# Awesome, we're done now.
recv_event.set()
self.tear_down()
class TestRequestsAdapter(SocketLevelTest):
# This uses HTTP/2.
h2 = True
def test_adapter_received_values(self, monkeypatch):
self.set_up()
# We need to patch the ssl_wrap_socket method to ensure that we
# forcefully upgrade.
old_wrap_socket = hyper.http11.connection.wrap_socket
def wrap(*args):
sock, _ = old_wrap_socket(*args)
return sock, 'h2'
monkeypatch.setattr(hyper.http11.connection, 'wrap_socket', wrap)
data = []
send_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# Do the handshake: conn header, settings, send settings, recv ack.
receive_preamble(sock)
# Now expect some data. One headers frame.
data.append(sock.recv(65535))
# Respond!
h = HeadersFrame(1)
h.data = self.get_encoder().encode({':status': 200, 'Content-Type': 'not/real', 'Content-Length': 20})
h.flags.add('END_HEADERS')
sock.send(h.serialize())
d = DataFrame(1)
d.data = b'1234567890' * 2
d.flags.add('END_STREAM')
sock.send(d.serialize())
send_event.wait()
sock.close()
self._start_server(socket_handler)
s = requests.Session()
s.mount('https://%s' % self.host, HTTP20Adapter())
r = s.get('https://%s:%s/some/path' % (self.host, self.port))
# Assert about the received values.
assert r.status_code == 200
assert r.headers[b'Content-Type'] == b'not/real'
assert r.content == b'1234567890' * 2
send_event.set()
self.tear_down()
def test_adapter_sending_values(self, monkeypatch):
self.set_up()
# We need to patch the ssl_wrap_socket method to ensure that we
# forcefully upgrade.
old_wrap_socket = hyper.http11.connection.wrap_socket
def wrap(*args):
sock, _ = old_wrap_socket(*args)
return sock, 'h2'
monkeypatch.setattr(hyper.http11.connection, 'wrap_socket', wrap)
data = []
send_event = threading.Event()
def socket_handler(listener):
sock = listener.accept()[0]
# Do the handshake: conn header, settings, send settings, recv ack.
receive_preamble(sock)
# Now expect some data. One headers frame and one data frame.
data.append(sock.recv(65535))
data.append(sock.recv(65535))
# Respond!
h = HeadersFrame(1)
h.data = self.get_encoder().encode({':status': 200, 'Content-Type': 'not/real', 'Content-Length': 20})
h.flags.add('END_HEADERS')
sock.send(h.serialize())
d = DataFrame(1)
d.data = b'1234567890' * 2
d.flags.add('END_STREAM')
sock.send(d.serialize())
send_event.set()
sock.close()
self._start_server(socket_handler)
s = requests.Session()
s.mount('https://%s' % self.host, HTTP20Adapter())
r = s.post(
'https://%s:%s/some/path' % (self.host, self.port),
data='hi there',
)
# Assert about the sent values.
assert r.status_code == 200
f = decode_frame(data[0])
assert isinstance(f, HeadersFrame)
f = decode_frame(data[1])
assert isinstance(f, DataFrame)
assert f.data == b'hi there'
self.tear_down()