Debian Codegraph @

test/test_http_client.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 import time
5 import socket
6 import sys
7 import subprocess
8 from urllib.parse import urlparse
9 import unittest
10 import threading
11 from test import NativeResourceTest
12 import ssl
13 import json
14 import os
15 from io import BytesIO
16 from http.server import HTTPServer, SimpleHTTPRequestHandler
17 from concurrent.futures import Future, thread
18 from awscrt.io import ClientBootstrap, ClientTlsContext, DefaultHostResolver, EventLoopGroup, TlsConnectionOptions, TlsContextOptions, TlsCipherPref
19 from awscrt.http import HttpClientConnection, HttpClientStreamBase, HttpHeaders, HttpProxyOptions, HttpRequest, HttpVersion, Http2ClientConnection, Http2Setting, Http2SettingID
20 import awscrt.exceptions
21
22
23 class Response:
24 """Holds contents of incoming response"""
25
26 def __init__(self):
27 self.status_code = None
28 self.headers = None
29 self.body = bytearray()
30
31 def on_response(self, http_stream, status_code, headers, **kwargs):
32 self.status_code = status_code
33 self.headers = HttpHeaders(headers)
34
35 def on_body(self, http_stream, chunk, **kwargs):
36 self.body.extend(chunk)
37
38
39 class TestRequestHandler(SimpleHTTPRequestHandler):
40 """Request handler for test server"""
41
42 def do_PUT(self):
43 content_length = int(self.headers['Content-Length'])
44 # store put request on the server object
45 incoming_body_bytes = self.rfile.read(content_length)
46 self.server.put_requests[self.path] = incoming_body_bytes
47 self.send_response(200, 'OK')
48 self.end_headers()
49
50
51 class LocalServerTestBase(NativeResourceTest):
52 """Base class for tests that use local HTTP/1.x server"""
53 hostname = 'localhost'
54 timeout = 5 # seconds
55
56 def _start_server(self, secure, http_1_0=False):
57 """Start local HTTP server"""
58 # HTTP/1.0 closes the connection at the end of each request
59 # HTTP/1.1 will keep the connection alive
60 if http_1_0:
61 TestRequestHandler.protocol_version = "HTTP/1.0"
62 else:
63 TestRequestHandler.protocol_version = "HTTP/1.1"
64
65 self.server = HTTPServer((self.hostname, 0), TestRequestHandler)
66 if secure:
67 context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
68 context.load_cert_chain(certfile='test/resources/unittest.crt', keyfile="test/resources/unittest.key")
69 self.server.socket = context.wrap_socket(self.server.socket, server_side=True)
70 self.port = self.server.server_address[1]
71
72 # put requests are stored in this dict
73 self.server.put_requests = {}
74
75 self.server_thread = threading.Thread(target=self.server.serve_forever, name='test_server')
76 self.server_thread.start()
77
78 def _stop_server(self):
79 """Stop local HTTP server"""
80 self.server.shutdown()
81 self.server.server_close()
82 self.server_thread.join()
83
84
85 class TestClient(LocalServerTestBase):
86
87 def _new_client_connection(self, secure, proxy_options=None, cipher_pref=TlsCipherPref.DEFAULT):
88 if secure:
89 tls_ctx_opt = TlsContextOptions()
90 tls_ctx_opt.cipher_pref = cipher_pref
91 tls_ctx_opt.verify_peer = False
92 tls_ctx = ClientTlsContext(tls_ctx_opt)
93 tls_conn_opt = tls_ctx.new_connection_options()
94 tls_conn_opt.set_server_name(self.hostname)
95 else:
96 tls_conn_opt = None
97
98 event_loop_group = EventLoopGroup()
99 host_resolver = DefaultHostResolver(event_loop_group)
100 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
101 connection_future = HttpClientConnection.new(host_name=self.hostname,
102 port=self.port,
103 bootstrap=bootstrap,
104 tls_connection_options=tls_conn_opt,
105 proxy_options=proxy_options)
106 return connection_future.result(self.timeout)
107
108 def _test_connect(self, secure, cipher_pref=TlsCipherPref.DEFAULT):
109 self._start_server(secure)
110 try:
111 connection = self._new_client_connection(secure, cipher_pref=cipher_pref)
112
113 # close connection
114 shutdown_error_from_close_future = connection.close().exception(self.timeout)
115
116 # assert that error was reported via close_future and shutdown callback
117 # error should be None (normal shutdown)
118 self.assertEqual(None, shutdown_error_from_close_future)
119 self.assertFalse(connection.is_open())
120
121 finally:
122 self._stop_server()
123
124 def test_connect_http(self):
125 self._test_connect(secure=False)
126
127 def test_connect_https(self):
128 self._test_connect(secure=True)
129
130 def _test_connection_closes_on_zero_refcount(self, secure):
131 # The connection should shut itself down cleanly when the GC collects the HttpClientConnection Python object.
132 self._start_server(secure)
133 try:
134 connection = self._new_client_connection(secure)
135
136 # referencing the shutdown_future does not keep the connection alive
137 close_future = connection.shutdown_future
138
139 # This should cause the GC to collect the HttpClientConnection
140 del connection
141
142 close_error = close_future.exception(self.timeout)
143 self.assertEqual(None, close_error)
144
145 finally:
146 self._stop_server()
147
148 def test_connection_closes_on_zero_refcount_http(self):
149 self._test_connection_closes_on_zero_refcount(secure=False)
150
151 def test_connection_closes_on_zero_refcount_https(self):
152 self._test_connection_closes_on_zero_refcount(secure=True)
153
154 def _test_get(self, secure, proxy_options=None):
155 # GET request receives this very file from the server. Super meta.
156
157 # Use HTTP/1.0 in proxy tests or server will keep connection with proxy alive
158 # and refuse to shut down for 1 minute at the end of each proxy test
159 http_1_0 = proxy_options is not None
160
161 self._start_server(secure, http_1_0)
162 try:
163 connection = self._new_client_connection(secure, proxy_options)
164
165 test_asset_path = 'test/test_http_client.py'
166
167 request = HttpRequest('GET', '/' + test_asset_path)
168 response = Response()
169 stream = connection.request(request, response.on_response, response.on_body)
170 stream.activate()
171
172 # wait for stream to complete
173 stream_completion_result = stream.completion_future.result(self.timeout)
174
175 self.assertEqual(200, response.status_code)
176 self.assertEqual(200, stream_completion_result)
177
178 with open(test_asset_path, 'rb') as test_asset:
179 test_asset_bytes = test_asset.read()
180 self.assertEqual(test_asset_bytes, response.body)
181
182 self.assertEqual(None, connection.close().exception(self.timeout))
183
184 finally:
185 self._stop_server()
186
187 def test_get_http(self):
188 self._test_get(secure=False)
189
190 def test_get_https(self):
191 self._test_get(secure=True)
192
193 def _test_shutdown_error(self, secure):
194 # Use HTTP/1.0 connection to force a SOCKET_CLOSED error after request completes
195 self._start_server(secure, http_1_0=True)
196 try:
197 connection = self._new_client_connection(secure)
198
199 # Send request, don't care what happens
200 request = HttpRequest('GET', '/')
201 response = Response()
202 stream = connection.request(request, response.on_response, response.on_body)
203 stream.activate()
204 stream.completion_future.result(self.timeout)
205
206 # Wait for server to hang up, which should be immediate since it's using HTTP/1.0
207 shutdown_error = connection.shutdown_future.exception(self.timeout)
208 self.assertIsInstance(shutdown_error, awscrt.exceptions.AwsCrtError)
209
210 finally:
211 self._stop_server()
212
213 def test_shutdown_error_http(self):
214 return self._test_shutdown_error(secure=False)
215
216 def test_shutdown_error_https(self):
217 return self._test_shutdown_error(secure=True)
218
219 def _test_put(self, secure):
220 # PUT request sends this very file to the server.
221 self._start_server(secure)
222 try:
223 connection = self._new_client_connection(secure)
224 test_asset_path = 'test/test_http_client.py'
225 with open(test_asset_path, 'rb') as outgoing_body_stream:
226 outgoing_body_bytes = outgoing_body_stream.read()
227 headers = HttpHeaders([
228 ('Content-Length', str(len(outgoing_body_bytes))),
229 ])
230
231 # seek back to start of stream before trying to send it
232 outgoing_body_stream.seek(0)
233
234 request = HttpRequest('PUT', '/' + test_asset_path, headers, outgoing_body_stream)
235 response = Response()
236 http_stream = connection.request(request, response.on_response, response.on_body)
237 http_stream.activate()
238 # wait for stream to complete
239 stream_completion_result = http_stream.completion_future.result(self.timeout)
240
241 self.assertEqual(200, response.status_code)
242 self.assertEqual(200, stream_completion_result)
243
244 # compare what we sent against what the server received
245 server_received = self.server.put_requests.get('/' + test_asset_path)
246 self.assertIsNotNone(server_received)
247 self.assertEqual(server_received, outgoing_body_bytes)
248
249 self.assertEqual(None, connection.close().result(self.timeout))
250
251 finally:
252 self._stop_server()
253
254 def test_put_http(self):
255 self._test_put(secure=False)
256
257 def test_put_https(self):
258 self._test_put(secure=True)
259
260 def _test_stream_lives_until_complete(self, secure):
261 # Ensure that stream and connection classes stay alive until work is complete
262 self._start_server(secure)
263 try:
264 connection = self._new_client_connection(secure)
265
266 request = HttpRequest('GET', '/test/test_http_client.py')
267 stream = connection.request(request)
268 stream.activate()
269 completion_future = stream.completion_future
270
271 # delete all local references
272 del stream
273 del connection
274
275 # stream should still complete successfully
276 completion_future.result(self.timeout)
277
278 finally:
279 self._stop_server()
280
281 def test_stream_lives_until_complete_http(self):
282 self._test_stream_lives_until_complete(secure=False)
283
284 def test_stream_lives_until_complete_https(self):
285 self._test_stream_lives_until_complete(secure=True)
286
287 def _test_request_lives_until_stream_complete(self, secure):
288 # Ensure HttpRequest and body InputStream stay alive until HttpClientStream completes (regression test)
289 self._start_server(secure)
290 try:
291 connection = self._new_client_connection(secure)
292
293 request = HttpRequest(
294 method='PUT',
295 path='/test/test_request_refcounts.txt',
296 headers=HttpHeaders([('Host', self.hostname), ('Content-Length', '5')]),
297 body_stream=BytesIO(b'hello'))
298
299 response = Response()
300 http_stream = connection.request(request, response.on_response, response.on_body)
301
302 # HttpClientStream should keep the dependencies (HttpRequest, HttpHeaders, InputStream)
303 # alive as long as it needs them
304 del request
305
306 http_stream.activate()
307 http_stream.completion_future.result(self.timeout)
308
309 self.assertEqual(None, connection.close().result(self.timeout))
310
311 finally:
312 self._stop_server()
313
314 def test_request_lives_until_stream_complete_http(self):
315 return self._test_request_lives_until_stream_complete(secure=False)
316
317 def test_request_lives_until_stream_complete_https(self):
318 return self._test_request_lives_until_stream_complete(secure=True)
319
320 def _test_stream_cleans_up_if_never_activated(self, secure):
321 # If a stream is never activated, it should just clean itself up
322 self._start_server(secure)
323 try:
324 connection = self._new_client_connection(secure)
325 stream = connection.request(HttpRequest('GET', '/test/test_http_client.py'))
326 # note we do NOT activate the stream
327
328 # delete local references, stream should clean itself up, connection should shut itself down
329 del stream
330 del connection
331
332 finally:
333 self._stop_server()
334
335 def test_stream_cleans_up_if_never_activated_http(self):
336 self._test_stream_cleans_up_if_never_activated(secure=False)
337
338 def test_stream_cleans_up_if_never_activated_https(self):
339 self._test_stream_cleans_up_if_never_activated(secure=True)
340
341 def _new_h2_client_connection(self, url):
342 event_loop_group = EventLoopGroup()
343 host_resolver = DefaultHostResolver(event_loop_group)
344 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
345
346 port = url.port
347 # only test https
348 if port is None:
349 port = 443
350 tls_ctx_options = TlsContextOptions()
351 tls_ctx_options.verify_peer = False # allow localhost
352 tls_ctx = ClientTlsContext(tls_ctx_options)
353 tls_conn_opt = tls_ctx.new_connection_options()
354 tls_conn_opt.set_server_name(url.hostname)
355 tls_conn_opt.set_alpn_list(["h2"])
356
357 connection_future = Http2ClientConnection.new(host_name=url.hostname,
358 port=port,
359 bootstrap=bootstrap,
360 tls_connection_options=tls_conn_opt)
361 return connection_future.result(self.timeout)
362
363 def test_h2_client(self):
364 url = urlparse("https://d1cz66xoahf9cl.cloudfront.net/http_test_doc.txt")
365 connection = self._new_h2_client_connection(url)
366 # check we set an h2 connection
367 self.assertEqual(connection.version, HttpVersion.Http2)
368
369 request = HttpRequest('GET', url.path)
370 request.headers.add('host', url.hostname)
371 response = Response()
372 stream = connection.request(request, response.on_response, response.on_body)
373 stream.activate()
374
375 # wait for stream to complete (use long timeout, it's a big file)
376 stream_completion_result = stream.completion_future.result(80)
377
378 # check result
379 self.assertEqual(200, response.status_code)
380 self.assertEqual(200, stream_completion_result)
381 self.assertEqual(14428801, len(response.body))
382
383 self.assertEqual(None, connection.close().exception(self.timeout))
384
385 def test_h2_manual_write_exception(self):
386 url = urlparse("https://d1cz66xoahf9cl.cloudfront.net/http_test_doc.txt")
387 connection = self._new_h2_client_connection(url)
388 # check we set an h2 connection
389 self.assertEqual(connection.version, HttpVersion.Http2)
390
391 request = HttpRequest('GET', url.path)
392 request.headers.add('host', url.hostname)
393 response = Response()
394 stream = connection.request(request, response.on_response, response.on_body)
395 stream.activate()
396 exception = None
397 try:
398 # If the stream is not configured to allow manual writes, this should throw an exception directly
399 stream.write_data(BytesIO(b'hello'), False)
400 except RuntimeError as e:
401 exception = e
402 self.assertIsNotNone(exception)
403
404 self.assertEqual(None, connection.close().exception(self.timeout))
405
406 @unittest.skipIf(not TlsCipherPref.PQ_DEFAULT.is_supported(), "Cipher pref not supported")
407 def test_connect_pq_default(self):
408 self._test_connect(secure=True, cipher_pref=TlsCipherPref.PQ_DEFAULT)
409
410
411 class MockServerTestBase(NativeResourceTest):
412 """Base class for tests that use the H2 mock server"""
413 timeout = 5 # seconds
414 p_server = None
415 mock_server_url = None
416
417 def setUp(self):
418 super().setUp()
419 # Start the mock server from the aws-c-http
420 server_path = os.path.join(
421 os.path.dirname(__file__),
422 '..',
423 'crt',
424 'aws-c-http',
425 'tests',
426 'mock_server',
427 'h2tls_mock_server.py')
428 python_path = sys.executable
429 self.mock_server_url = urlparse("https://localhost:3443/echo")
430 self.p_server = subprocess.Popen([python_path, server_path])
431 # Wait for server to be ready
432 self._wait_for_server_ready()
433
434 def _wait_for_server_ready(self):
435 """Wait until server is accepting connections."""
436 max_attempts = 20
437 for attempt in range(max_attempts):
438 try:
439 with socket.create_connection(("127.0.0.1", self.mock_server_url.port), timeout=1):
440 return # Server is ready
441 except (ConnectionRefusedError, socket.timeout):
442 time.sleep(0.5)
443
444 # If we get here, server failed to start
445 stdout, stderr = self.p_server.communicate(timeout=0.5)
446 raise RuntimeError(f"Server failed to start after {max_attempts} attempts.\n"
447 f"STDOUT: {stdout.decode()}\nSTDERR: {stderr.decode()}")
448
449 def tearDown(self):
450 self.p_server.terminate()
451 try:
452 self.p_server.wait(timeout=5)
453 except subprocess.TimeoutExpired:
454 self.p_server.kill()
455 super().tearDown()
456
457 def _new_mock_h2_connection(self, manual_window_management=False, initial_window_size=None, initial_settings=None):
458 """Create HTTP/2 client connection to local mock server"""
459 event_loop_group = EventLoopGroup()
460 host_resolver = DefaultHostResolver(event_loop_group)
461 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
462
463 port = self.mock_server_url.port
464 if port is None:
465 port = 443
466
467 tls_ctx_options = TlsContextOptions()
468 tls_ctx_options.verify_peer = False
469 tls_ctx = ClientTlsContext(tls_ctx_options)
470 tls_conn_opt = tls_ctx.new_connection_options()
471 tls_conn_opt.set_server_name(self.mock_server_url.hostname)
472 tls_conn_opt.set_alpn_list(["h2"])
473
474 if initial_settings is None:
475 initial_settings = [Http2Setting(Http2SettingID.ENABLE_PUSH, 0)]
476
477 kwargs = {
478 'host_name': self.mock_server_url.hostname,
479 'port': port,
480 'bootstrap': bootstrap,
481 'tls_connection_options': tls_conn_opt,
482 'initial_settings': initial_settings,
483 'manual_window_management': manual_window_management
484 }
485 if initial_window_size is not None:
486 kwargs['initial_window_size'] = initial_window_size
487
488 connection_future = Http2ClientConnection.new(**kwargs)
489 return connection_future.result(self.timeout)
490
491
492 @unittest.skipUnless(os.environ.get('AWS_TEST_LOCALHOST'), 'set env var to run test: AWS_TEST_LOCALHOST')
493 class TestClientMockServer(MockServerTestBase):
494
495 def _on_remote_settings_changed(self, settings):
496 # The mock server has the default settings with
497 # ENABLE_PUSH = 0
498 # MAX_CONCURRENT_STREAMS = 100
499 # MAX_HEADER_LIST_SIZE = 2**16
500 # Check the settings here
501 self.assertEqual(len(settings), 3)
502 for i in settings:
503 if i.id == Http2SettingID.ENABLE_PUSH:
504 self.assertEqual(i.value, 0)
505 if i.id == Http2SettingID.MAX_CONCURRENT_STREAMS:
506 self.assertEqual(i.value, 100)
507 if i.id == Http2SettingID.MAX_HEADER_LIST_SIZE:
508 self.assertEqual(i.value, 2**16)
509
510 def _new_mock_connection(self, initial_settings=None):
511 """Create connection with remote settings callback"""
512 kwargs = {'initial_settings': initial_settings}
513 connection_future = Http2ClientConnection.new(
514 host_name=self.mock_server_url.hostname,
515 port=self.mock_server_url.port if self.mock_server_url.port else 443,
516 bootstrap=self._create_client_bootstrap(),
517 tls_connection_options=self._create_tls_connection_options(),
518 initial_settings=initial_settings if initial_settings else [Http2Setting(Http2SettingID.ENABLE_PUSH, 0)],
519 on_remote_settings_changed=self._on_remote_settings_changed)
520 return connection_future.result(self.timeout)
521
522 def _create_client_bootstrap(self):
523 """Create client bootstrap"""
524 event_loop_group = EventLoopGroup()
525 host_resolver = DefaultHostResolver(event_loop_group)
526 return ClientBootstrap(event_loop_group, host_resolver)
527
528 def _create_tls_connection_options(self):
529 """Create TLS connection options for mock server"""
530 tls_ctx_options = TlsContextOptions()
531 tls_ctx_options.verify_peer = False
532 tls_ctx = ClientTlsContext(tls_ctx_options)
533 tls_conn_opt = tls_ctx.new_connection_options()
534 tls_conn_opt.set_server_name(self.mock_server_url.hostname)
535 tls_conn_opt.set_alpn_list(["h2"])
536 return tls_conn_opt
537
538 def test_h2_mock_server_manual_write(self):
539 connection = self._new_mock_connection()
540 # check we set an h2 connection
541 self.assertEqual(connection.version, HttpVersion.Http2)
542
543 request = HttpRequest('POST', self.mock_server_url.path)
544 request.headers.add('host', self.mock_server_url.hostname)
545 response = Response()
546 stream = connection.request(request, response.on_response, response.on_body, manual_write=True)
547 stream.activate()
548 exception = None
549 body_chunks = [b'hello', b'he123123', b'hello']
550 total_length = 0
551 content = b''
552 for i in body_chunks:
553 total_length = total_length + len(i)
554 content += i
555 try:
556 # If the stream is not configured to allow manual writes, this should throw an exception directly
557 f = stream.write_data(BytesIO(body_chunks[0]), False)
558 f.result(self.timeout)
559 stream.write_data(BytesIO(body_chunks[1]), False)
560 stream.write_data(None, False)
561 stream.write_data(BytesIO(body_chunks[2]), True)
562 except RuntimeError as e:
563 exception = e
564 self.assertIsNone(exception)
565 stream_completion_result = stream.completion_future.result(80)
566 # check result
567 self.assertEqual(200, response.status_code)
568 self.assertEqual(200, stream_completion_result)
569 # Parse the response from mock server which has format:
570 # {
571 # "body": <str of data received>,
572 # "bytes": <byte count of data received>
573 # }
574 parsed_response = json.loads(response.body.decode())
575 self.assertEqual(total_length, int(parsed_response["bytes"]))
576 self.assertEqual(content.decode(), parsed_response["body"])
577
578 self.assertEqual(None, connection.close().exception(self.timeout))
579
580 class DelayStream:
581 def __init__(self, bad_read=False):
582 self._read = False
583 self.bad_read = bad_read
584
585 def read(self, _len):
586 if self.bad_read:
587 # simulate a bad read that raises an exception
588 # this will cause the stream to fail
589 raise RuntimeError("bad read exception")
590 if self._read:
591 # return empty as EOS
592 return b''
593 else:
594 self._read = True
595 return b'hello'
596
597 def test_h2_mock_server_manual_write_read_exception(self):
598 connection = self._new_mock_connection()
599 # check we set an h2 connection
600 self.assertEqual(connection.version, HttpVersion.Http2)
601
602 request = HttpRequest('POST', self.mock_server_url.path)
603 request.headers.add('host', self.mock_server_url.hostname)
604 response = Response()
605 stream = connection.request(request, response.on_response, response.on_body, manual_write=True)
606 stream.activate()
607 exception = None
608 data = self.DelayStream(bad_read=True)
609 try:
610 f = stream.write_data(data, False)
611 f.result(self.timeout)
612 except Exception as e:
613 # future will raise the exception from the write_data call.
614 exception = e
615 self.assertIsNotNone(exception)
616 # stream will complete with same exception.
617 stream_completion_exception = stream.completion_future.exception()
618 self.assertIsNotNone(stream_completion_exception)
619 # assert that the exception is the same as the one we got from write_data.
620 self.assertEqual(str(exception), str(stream_completion_exception))
621 self.assertEqual(None, connection.close().exception(self.timeout))
622
623 def test_h2_mock_server_manual_write_lifetime(self):
624 connection = self._new_mock_connection()
625 # check we set an h2 connection
626 self.assertEqual(connection.version, HttpVersion.Http2)
627
628 request = HttpRequest('POST', self.mock_server_url.path)
629 request.headers.add('host', self.mock_server_url.hostname)
630 response = Response()
631 stream = connection.request(request, response.on_response, response.on_body, manual_write=True)
632 stream.activate()
633 exception = None
634 data = self.DelayStream(bad_read=False)
635 try:
636 f = stream.write_data(data, False)
637 # make sure when the python object was dropped, things are still ok
638 del data
639 f.result(self.timeout)
640 f = stream.write_data(None, True)
641 f.result(self.timeout)
642 except Exception as e:
643 # future will raise the exception from the write_data call.
644 exception = e
645 self.assertIsNone(exception)
646 # stream will complete with another exception.
647 stream.completion_future.result()
648 self.assertEqual(None, connection.close().exception(self.timeout))
649
650 def test_h2_mock_server_settings(self):
651 exception = None
652 try:
653 # invalid settings, should throw an exception
654 initial_settings = [100]
655 connection = self._new_mock_connection(initial_settings)
656 except Exception as e:
657 exception = e
658 self.assertIsNotNone(exception)
659
660 connection = self._new_mock_connection()
661 # check we set an h2 connection
662 self.assertEqual(connection.version, HttpVersion.Http2)
663
664 request = HttpRequest('POST', self.mock_server_url.path)
665 request.headers.add('host', self.mock_server_url.hostname)
666 response = Response()
667 stream = connection.request(request, response.on_response, response.on_body, manual_write=True)
668 stream.activate()
669 exception = None
670 stream.write_data(BytesIO(b'hello'), True)
671
672 self.assertIsNone(exception)
673 stream_completion_result = stream.completion_future.result(80)
674 # check result
675 self.assertEqual(200, response.status_code)
676 self.assertEqual(200, stream_completion_result)
677 print(response.body)
678
679 self.assertEqual(None, connection.close().exception(self.timeout))
680
681
682 class Response:
683 def __init__(self):
684 self.status_code = None
685 self.headers = None
686 self.body = bytearray()
687
688 def on_response(self, http_stream, status_code, headers, **kwargs):
689 self.status_code = status_code
690 self.headers = HttpHeaders(headers)
691
692 def on_body(self, http_stream, chunk, **kwargs):
693 self.body.extend(chunk)
694
695
696 class FlowControlTest(LocalServerTestBase):
697 """HTTP/1.1 flow control tests using local server"""
698 timeout = 10.0
699
700 def _new_h1_client_connection(
701 self,
702 secure,
703 manual_window_management=False,
704 initial_window_size=None,
705 read_buffer_capacity=None):
706 """Create HTTP/1.1 client connection to local server"""
707 if secure:
708 tls_ctx_opt = TlsContextOptions()
709 tls_ctx_opt.verify_peer = False
710 tls_ctx = ClientTlsContext(tls_ctx_opt)
711 tls_conn_opt = tls_ctx.new_connection_options()
712 tls_conn_opt.set_server_name(self.hostname)
713 else:
714 tls_conn_opt = None
715
716 event_loop_group = EventLoopGroup()
717 host_resolver = DefaultHostResolver(event_loop_group)
718 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
719
720 kwargs = {
721 'host_name': self.hostname,
722 'port': self.port,
723 'bootstrap': bootstrap,
724 'tls_connection_options': tls_conn_opt,
725 'manual_window_management': manual_window_management
726 }
727 if initial_window_size is not None:
728 kwargs['initial_window_size'] = initial_window_size
729 if read_buffer_capacity is not None:
730 kwargs['read_buffer_capacity'] = read_buffer_capacity
731
732 connection_future = HttpClientConnection.new(**kwargs)
733 return connection_future.result(self.timeout)
734
735 def test_h1_manual_window_management_happy_path(self):
736 """Test HTTP/1.1 manual window management happy path"""
737 self._start_server(secure=True)
738 try:
739 connection = self._new_h1_client_connection(
740 secure=True,
741 manual_window_management=True,
742 initial_window_size=5,
743 read_buffer_capacity=1000
744 )
745
746 # Create a file with known size for testing
747 test_data = b'0123456789' # 10 bytes
748 test_file_path = 'test_flow_control_data.txt'
749 with open(test_file_path, 'wb') as f:
750 f.write(test_data)
751
752 try:
753 request = HttpRequest('GET', '/' + test_file_path)
754 request.headers.add('host', self.hostname)
755
756 response = Response()
757 received_chunks = []
758 window_updates_sent = []
759
760 def on_body_with_window_update(http_stream, chunk, **kwargs):
761 received_chunks.append(len(chunk))
762 response.body.extend(chunk)
763 http_stream.update_window(len(chunk))
764 window_updates_sent.append(len(chunk))
765
766 stream = connection.request(request, response.on_response, on_body_with_window_update)
767 stream.activate()
768 stream_completion_result = stream.completion_future.result(timeout=self.timeout)
769
770 self.assertEqual(200, response.status_code)
771 self.assertEqual(200, stream_completion_result)
772 self.assertEqual(test_data, bytes(response.body))
773 self.assertGreater(len(received_chunks), 0, "No data chunks received")
774 self.assertGreater(len(window_updates_sent), 0, "No window updates sent")
775 self.assertEqual(sum(received_chunks), sum(window_updates_sent),
776 "Window updates don't match received data")
777
778 self.assertEqual(None, connection.close().result(self.timeout))
779 finally:
780 # Clean up test file
781 if os.path.exists(test_file_path):
782 os.remove(test_file_path)
783 finally:
784 self._stop_server()
785
786 def test_h1_stream_flow_control_blocks_and_resumes(self):
787 """Test that HTTP/1.1 stream flow control actually blocks and resumes"""
788 self._start_server(secure=True)
789 try:
790 connection = self._new_h1_client_connection(
791 secure=True,
792 manual_window_management=True,
793 initial_window_size=1,
794 read_buffer_capacity=1000
795 )
796
797 # Create a file with 100 bytes for testing
798 test_data = bytes(range(100))
799 test_file_path = 'test_flow_control_100.txt'
800 with open(test_file_path, 'wb') as f:
801 f.write(test_data)
802
803 try:
804 request = HttpRequest('GET', '/' + test_file_path)
805 request.headers.add('host', self.hostname)
806
807 response = Response()
808 chunks_received = []
809
810 def on_body(http_stream, chunk, **kwargs):
811 chunks_received.append(len(chunk))
812 response.body.extend(chunk)
813 http_stream.update_window(len(chunk))
814
815 stream = connection.request(request, response.on_response, on_body)
816 stream.activate()
817 stream.completion_future.result(timeout=self.timeout)
818
819 self.assertEqual(test_data, bytes(response.body))
820 # With window=1, we should receive many small chunks
821 self.assertGreater(len(chunks_received), 1, "Should receive multiple chunks with tiny window")
822
823 self.assertEqual(None, connection.close().result(self.timeout))
824 finally:
825 # Clean up test file
826 if os.path.exists(test_file_path):
827 os.remove(test_file_path)
828 finally:
829 self._stop_server()
830
831
832 @unittest.skipUnless(os.environ.get('AWS_TEST_LOCALHOST'), 'set env var to run test: AWS_TEST_LOCALHOST')
833 class FlowControlH2Test(MockServerTestBase):
834 """HTTP/2 flow control tests using local mock server"""
835 timeout = 10.0
836
837 def test_h2_manual_window_management_happy_path(self):
838 """Test HTTP/2 manual window management happy path"""
839 connection = self._new_mock_h2_connection(
840 manual_window_management=True,
841 initial_window_size=65536
842 )
843
844 # GET request with x-repeat-data header to download data
845 request = HttpRequest('GET', self.mock_server_url.path)
846 request.headers.add('host', self.mock_server_url.hostname)
847 request.headers.add('x-repeat-data', '100') # Request 100 bytes of data
848
849 response = Response()
850 received_chunks = []
851 window_updates_sent = []
852
853 def on_body_with_window_update(http_stream, chunk, **kwargs):
854 received_chunks.append(len(chunk))
855 response.body.extend(chunk)
856 http_stream.update_window(len(chunk))
857 window_updates_sent.append(len(chunk))
858
859 stream = connection.request(request, response.on_response, on_body_with_window_update)
860 stream.activate()
861
862 stream_completion_result = stream.completion_future.result(timeout=self.timeout)
863
864 self.assertEqual(200, response.status_code)
865 self.assertEqual(200, stream_completion_result)
866 self.assertGreater(len(response.body), 0, "No response body received")
867 self.assertGreater(len(received_chunks), 0, "No data chunks received")
868 self.assertGreater(len(window_updates_sent), 0, "No window updates sent")
869
870 self.assertEqual(None, connection.close().result(self.timeout))
871
872 def test_h2_stream_flow_control_blocks_and_resumes(self):
873 """Test that HTTP/2 stream flow control actually blocks and resumes"""
874 connection = self._new_mock_h2_connection(
875 manual_window_management=True,
876 initial_window_size=10 # Small window to force multiple chunks
877 )
878
879 # GET request with x-repeat-data header to download data
880 request = HttpRequest('GET', self.mock_server_url.path)
881 request.headers.add('host', self.mock_server_url.hostname)
882 request.headers.add('x-repeat-data', '100') # Request 100 bytes of data
883
884 response = Response()
885 chunks_received = []
886
887 def on_body(http_stream, chunk, **kwargs):
888 chunks_received.append(len(chunk))
889 response.body.extend(chunk)
890 # Update window to allow more data
891 http_stream.update_window(len(chunk))
892
893 stream = connection.request(request, response.on_response, on_body)
894 stream.activate()
895
896 stream.completion_future.result(timeout=self.timeout)
897
898 self.assertEqual(200, response.status_code)
899 self.assertGreater(len(response.body), 0, "No response body received")
900 # With small window, we should receive multiple chunks
901 self.assertGreater(len(chunks_received), 1, "Should receive multiple chunks with small window")
902
903 self.assertEqual(None, connection.close().result(self.timeout))
904
905
906 class Http2RemoteEndStreamTest(NativeResourceTest):
907 """Test suite for HTTP/2 on_h2_remote_end_stream callback"""
908 timeout = 10 # seconds
909
910 def _new_httpbin_h2_connection(self):
911 """Create HTTP/2 connection to httpbin.org"""
912 event_loop_group = EventLoopGroup()
913 host_resolver = DefaultHostResolver(event_loop_group)
914 bootstrap = ClientBootstrap(event_loop_group, host_resolver)
915
916 tls_ctx_options = TlsContextOptions()
917 tls_ctx = ClientTlsContext(tls_ctx_options)
918 tls_conn_opt = tls_ctx.new_connection_options()
919 tls_conn_opt.set_server_name("httpbin.org")
920 tls_conn_opt.set_alpn_list(["h2"])
921
922 connection_future = Http2ClientConnection.new(
923 host_name="httpbin.org",
924 port=443,
925 bootstrap=bootstrap,
926 tls_connection_options=tls_conn_opt)
927
928 return connection_future.result(self.timeout)
929
930 def test_h2_remote_end_stream_ordering(self):
931 """Test that on_h2_remote_end_stream fires before on_complete when server finishes first"""
932 connection = self._new_httpbin_h2_connection()
933
934 # Use httpbin.org 404 path - server responds immediately
935 request = HttpRequest('POST', '/this-path-does-not-exist-deliberately-404')
936 request.headers.add('host', 'httpbin.org')
937 response = Response()
938
939 stream = connection.request(request, response.on_response, response.on_body, manual_write=True)
940 stream.activate()
941
942 # Send first chunk WITHOUT end_stream - keeping the client side open
943 stream.write_data(BytesIO(b'chunk1'), end_stream=False).result(self.timeout)
944
945 # Wait for server to finish (remote_end_stream_future completes)
946 # Server will respond immediately with 404 and send END_STREAM
947 remote_result = stream.remote_end_stream_future.result(self.timeout)
948 self.assertIsNone(remote_result, "remote_end_stream_future should complete with None")
949
950 # Verify completion_future has NOT completed yet (stream still open)
951 self.assertFalse(stream.completion_future.done(),
952 "completion_future should not be done until client closes")
953
954 # Now send final chunk WITH end_stream to close client side
955 stream.write_data(BytesIO(b'chunk2'), end_stream=True).result(self.timeout)
956
957 # Wait for stream completion
958 completion_result = stream.completion_future.result(self.timeout)
959 self.assertEqual(404, completion_result, "Should get 404 status code")
960
961 connection.close().result(self.timeout)
962
963
964 if __name__ == '__main__':
965 unittest.main()