| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
import time |
| 5 |
import socket |
| 6 |
import sys |
| 7 |
import asyncio |
| 8 |
import unittest |
| 9 |
import threading |
| 10 |
import subprocess |
| 11 |
import concurrent.futures |
| 12 |
from urllib.parse import urlparse |
| 13 |
from test import NativeResourceTest |
| 14 |
import ssl |
| 15 |
import os |
| 16 |
import json |
| 17 |
from io import BytesIO |
| 18 |
from http.server import HTTPServer, SimpleHTTPRequestHandler |
| 19 |
from awscrt import io |
| 20 |
from awscrt.io import ClientBootstrap, ClientTlsContext, DefaultHostResolver, EventLoopGroup, TlsContextOptions, TlsCipherPref |
| 21 |
from awscrt.http import HttpHeaders, HttpRequest, HttpVersion, Http2Setting, Http2SettingID |
| 22 |
from awscrt.aio.http import AIOHttpClientConnection, AIOHttp2ClientConnection |
| 23 |
import threading |
| 24 |
|
| 25 |
|
| 26 |
class Response: |
| 27 |
"""Holds contents of incoming response""" |
| 28 |
|
| 29 |
def __init__(self): |
| 30 |
self.status_code = None |
| 31 |
self.headers = None |
| 32 |
self.body = bytearray() |
| 33 |
|
| 34 |
async def collect_response(self, stream): |
| 35 |
"""Collects complete response from a stream""" |
| 36 |
|
| 37 |
self.status_code = await stream.get_response_status_code() |
| 38 |
headers_list = await stream.get_response_headers() |
| 39 |
self.headers = HttpHeaders(headers_list) |
| 40 |
|
| 41 |
while True: |
| 42 |
chunk = await stream.get_next_response_chunk() |
| 43 |
if not chunk: |
| 44 |
break |
| 45 |
self.body.extend(chunk) |
| 46 |
if hasattr(stream, 'update_window'): |
| 47 |
stream.update_window(len(chunk)) |
| 48 |
|
| 49 |
|
| 50 |
return self.status_code |
| 51 |
|
| 52 |
|
| 53 |
class TestRequestHandler(SimpleHTTPRequestHandler): |
| 54 |
"""Request handler for test server""" |
| 55 |
|
| 56 |
def do_PUT(self): |
| 57 |
content_length = int(self.headers['Content-Length']) |
| 58 |
|
| 59 |
incoming_body_bytes = self.rfile.read(content_length) |
| 60 |
self.server.put_requests[self.path] = incoming_body_bytes |
| 61 |
self.send_response(200, 'OK') |
| 62 |
self.end_headers() |
| 63 |
|
| 64 |
|
| 65 |
class AsyncLocalServerTestBase(NativeResourceTest): |
| 66 |
"""Base class for async tests that use local HTTP/1.x server""" |
| 67 |
hostname = 'localhost' |
| 68 |
timeout = 5 |
| 69 |
|
| 70 |
def _start_server(self, secure, http_1_0=False): |
| 71 |
"""Start local HTTP server""" |
| 72 |
|
| 73 |
|
| 74 |
if http_1_0: |
| 75 |
TestRequestHandler.protocol_version = "HTTP/1.0" |
| 76 |
else: |
| 77 |
TestRequestHandler.protocol_version = "HTTP/1.1" |
| 78 |
|
| 79 |
self.server = HTTPServer((self.hostname, 0), TestRequestHandler) |
| 80 |
if secure: |
| 81 |
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 82 |
context.minimum_version = ssl.TLSVersion.TLSv1_2 |
| 83 |
context.load_cert_chain(certfile='test/resources/unittest.crt', keyfile="test/resources/unittest.key") |
| 84 |
self.server.socket = context.wrap_socket(self.server.socket, server_side=True) |
| 85 |
self.port = self.server.server_address[1] |
| 86 |
|
| 87 |
|
| 88 |
self.server.put_requests = {} |
| 89 |
|
| 90 |
self.server_thread = threading.Thread(target=self.server.serve_forever, name='test_server') |
| 91 |
self.server_thread.start() |
| 92 |
|
| 93 |
def _stop_server(self): |
| 94 |
"""Stop local HTTP server""" |
| 95 |
self.server.shutdown() |
| 96 |
self.server.server_close() |
| 97 |
self.server_thread.join() |
| 98 |
|
| 99 |
|
| 100 |
class TestAsyncClient(AsyncLocalServerTestBase): |
| 101 |
|
| 102 |
async def _new_client_connection(self, secure, proxy_options=None): |
| 103 |
if secure: |
| 104 |
tls_ctx_opt = TlsContextOptions() |
| 105 |
tls_ctx_opt.verify_peer = False |
| 106 |
tls_ctx = ClientTlsContext(tls_ctx_opt) |
| 107 |
tls_conn_opt = tls_ctx.new_connection_options() |
| 108 |
tls_conn_opt.set_server_name(self.hostname) |
| 109 |
else: |
| 110 |
tls_conn_opt = None |
| 111 |
|
| 112 |
event_loop_group = EventLoopGroup() |
| 113 |
host_resolver = DefaultHostResolver(event_loop_group) |
| 114 |
bootstrap = ClientBootstrap(event_loop_group, host_resolver) |
| 115 |
return await AIOHttpClientConnection.new( |
| 116 |
host_name=self.hostname, |
| 117 |
port=self.port, |
| 118 |
bootstrap=bootstrap, |
| 119 |
tls_connection_options=tls_conn_opt, |
| 120 |
proxy_options=proxy_options) |
| 121 |
|
| 122 |
async def _test_connect(self, secure): |
| 123 |
self._start_server(secure) |
| 124 |
try: |
| 125 |
connection = await self._new_client_connection(secure) |
| 126 |
|
| 127 |
|
| 128 |
await connection.close() |
| 129 |
self.assertFalse(connection.is_open()) |
| 130 |
|
| 131 |
finally: |
| 132 |
self._stop_server() |
| 133 |
|
| 134 |
async def _test_get(self, secure): |
| 135 |
|
| 136 |
self._start_server(secure) |
| 137 |
try: |
| 138 |
connection = await self._new_client_connection(secure) |
| 139 |
self.assertTrue(connection.is_open()) |
| 140 |
|
| 141 |
test_asset_path = 'test/test_aiohttp_client.py' |
| 142 |
|
| 143 |
|
| 144 |
request = HttpRequest('GET', '/' + test_asset_path) |
| 145 |
stream = connection.request(request) |
| 146 |
|
| 147 |
|
| 148 |
response = Response() |
| 149 |
status_code = await response.collect_response(stream) |
| 150 |
|
| 151 |
|
| 152 |
self.assertEqual(200, status_code) |
| 153 |
self.assertEqual(200, response.status_code) |
| 154 |
|
| 155 |
with open(test_asset_path, 'rb') as test_asset: |
| 156 |
test_asset_bytes = test_asset.read() |
| 157 |
self.assertEqual(test_asset_bytes, response.body) |
| 158 |
|
| 159 |
await connection.close() |
| 160 |
|
| 161 |
finally: |
| 162 |
self._stop_server() |
| 163 |
|
| 164 |
async def _test_put(self, secure): |
| 165 |
|
| 166 |
self._start_server(secure) |
| 167 |
try: |
| 168 |
connection = await self._new_client_connection(secure) |
| 169 |
test_asset_path = 'test/test_aiohttp_client.py' |
| 170 |
with open(test_asset_path, 'rb') as outgoing_body_stream: |
| 171 |
outgoing_body_bytes = outgoing_body_stream.read() |
| 172 |
headers = HttpHeaders([ |
| 173 |
('Content-Length', str(len(outgoing_body_bytes))), |
| 174 |
]) |
| 175 |
|
| 176 |
|
| 177 |
outgoing_body_stream.seek(0) |
| 178 |
|
| 179 |
|
| 180 |
request = HttpRequest('PUT', '/' + test_asset_path, headers, outgoing_body_stream) |
| 181 |
stream = connection.request(request) |
| 182 |
|
| 183 |
|
| 184 |
response = Response() |
| 185 |
status_code = await response.collect_response(stream) |
| 186 |
|
| 187 |
|
| 188 |
self.assertEqual(200, status_code) |
| 189 |
self.assertEqual(200, response.status_code) |
| 190 |
|
| 191 |
|
| 192 |
server_received = self.server.put_requests.get('/' + test_asset_path) |
| 193 |
self.assertIsNotNone(server_received) |
| 194 |
self.assertEqual(server_received, outgoing_body_bytes) |
| 195 |
|
| 196 |
await connection.close() |
| 197 |
|
| 198 |
finally: |
| 199 |
self._stop_server() |
| 200 |
|
| 201 |
async def _test_shutdown_error(self, secure): |
| 202 |
|
| 203 |
self._start_server(secure, http_1_0=True) |
| 204 |
try: |
| 205 |
connection = await self._new_client_connection(secure) |
| 206 |
|
| 207 |
|
| 208 |
request = HttpRequest('GET', '/') |
| 209 |
stream = connection.request(request) |
| 210 |
|
| 211 |
|
| 212 |
response = Response() |
| 213 |
await response.collect_response(stream) |
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
await asyncio.sleep(0.5) |
| 218 |
self.assertFalse(connection.is_open()) |
| 219 |
|
| 220 |
finally: |
| 221 |
self._stop_server() |
| 222 |
|
| 223 |
async def _test_stream_lives_until_complete(self, secure): |
| 224 |
|
| 225 |
self._start_server(secure) |
| 226 |
try: |
| 227 |
connection = await self._new_client_connection(secure) |
| 228 |
|
| 229 |
request = HttpRequest('GET', '/test/test_aiohttp_client.py') |
| 230 |
stream = connection.request(request) |
| 231 |
|
| 232 |
|
| 233 |
response = Response() |
| 234 |
|
| 235 |
|
| 236 |
collect_task = asyncio.create_task(response.collect_response(stream)) |
| 237 |
|
| 238 |
|
| 239 |
del stream |
| 240 |
del connection |
| 241 |
|
| 242 |
|
| 243 |
status_code = await collect_task |
| 244 |
self.assertEqual(200, status_code) |
| 245 |
|
| 246 |
finally: |
| 247 |
self._stop_server() |
| 248 |
|
| 249 |
async def _test_request_lives_until_stream_complete(self, secure): |
| 250 |
|
| 251 |
self._start_server(secure) |
| 252 |
try: |
| 253 |
connection = await self._new_client_connection(secure) |
| 254 |
|
| 255 |
request = HttpRequest( |
| 256 |
method='PUT', |
| 257 |
path='/test/test_request_refcounts.txt', |
| 258 |
headers=HttpHeaders([('Host', self.hostname), ('Content-Length', '5')]), |
| 259 |
body_stream=BytesIO(b'hello')) |
| 260 |
|
| 261 |
|
| 262 |
stream = connection.request(request) |
| 263 |
del request |
| 264 |
|
| 265 |
|
| 266 |
response = Response() |
| 267 |
status_code = await response.collect_response(stream) |
| 268 |
self.assertEqual(200, status_code) |
| 269 |
|
| 270 |
await connection.close() |
| 271 |
|
| 272 |
finally: |
| 273 |
self._stop_server() |
| 274 |
|
| 275 |
async def _new_h2_client_connection(self, url): |
| 276 |
event_loop_group = EventLoopGroup() |
| 277 |
host_resolver = DefaultHostResolver(event_loop_group) |
| 278 |
bootstrap = ClientBootstrap(event_loop_group, host_resolver) |
| 279 |
|
| 280 |
port = url.port |
| 281 |
if port is None: |
| 282 |
port = 443 |
| 283 |
|
| 284 |
tls_ctx_options = TlsContextOptions() |
| 285 |
tls_ctx_options.verify_peer = False |
| 286 |
tls_ctx = ClientTlsContext(tls_ctx_options) |
| 287 |
tls_conn_opt = tls_ctx.new_connection_options() |
| 288 |
tls_conn_opt.set_server_name(url.hostname) |
| 289 |
tls_conn_opt.set_alpn_list(["h2"]) |
| 290 |
|
| 291 |
connection = await AIOHttp2ClientConnection.new( |
| 292 |
host_name=url.hostname, |
| 293 |
port=port, |
| 294 |
bootstrap=bootstrap, |
| 295 |
tls_connection_options=tls_conn_opt) |
| 296 |
|
| 297 |
return connection |
| 298 |
|
| 299 |
async def _test_h2_client(self): |
| 300 |
url = urlparse("https://d1cz66xoahf9cl.cloudfront.net/http_test_doc.txt") |
| 301 |
connection = await self._new_h2_client_connection(url) |
| 302 |
|
| 303 |
|
| 304 |
self.assertEqual(connection.version, HttpVersion.Http2) |
| 305 |
|
| 306 |
request = HttpRequest('GET', url.path) |
| 307 |
request.headers.add('host', url.hostname) |
| 308 |
stream = connection.request(request) |
| 309 |
|
| 310 |
response = Response() |
| 311 |
status_code = await response.collect_response(stream) |
| 312 |
|
| 313 |
|
| 314 |
self.assertEqual(200, status_code) |
| 315 |
self.assertEqual(200, response.status_code) |
| 316 |
self.assertEqual(14428801, len(response.body)) |
| 317 |
|
| 318 |
await connection.close() |
| 319 |
|
| 320 |
async def _test_h2_manual_write_exception(self): |
| 321 |
url = urlparse("https://d1cz66xoahf9cl.cloudfront.net/http_test_doc.txt") |
| 322 |
connection = await self._new_h2_client_connection(url) |
| 323 |
|
| 324 |
|
| 325 |
self.assertEqual(connection.version, HttpVersion.Http2) |
| 326 |
|
| 327 |
request = HttpRequest('GET', url.path) |
| 328 |
request.headers.add('host', url.hostname) |
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
stream = connection.request(request) |
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
exception = None |
| 337 |
try: |
| 338 |
|
| 339 |
|
| 340 |
await stream._write_data(BytesIO(b'hello'), False) |
| 341 |
except (RuntimeError, AttributeError) as e: |
| 342 |
exception = e |
| 343 |
|
| 344 |
self.assertIsNotNone(exception) |
| 345 |
await connection.close() |
| 346 |
|
| 347 |
def test_connect_http(self): |
| 348 |
asyncio.run(self._test_connect(secure=False)) |
| 349 |
|
| 350 |
def test_connect_https(self): |
| 351 |
asyncio.run(self._test_connect(secure=True)) |
| 352 |
|
| 353 |
def test_get_http(self): |
| 354 |
asyncio.run(self._test_get(secure=False)) |
| 355 |
|
| 356 |
def test_get_https(self): |
| 357 |
asyncio.run(self._test_get(secure=True)) |
| 358 |
|
| 359 |
def test_put_http(self): |
| 360 |
asyncio.run(self._test_put(secure=False)) |
| 361 |
|
| 362 |
def test_put_https(self): |
| 363 |
asyncio.run(self._test_put(secure=True)) |
| 364 |
|
| 365 |
def test_shutdown_error_http(self): |
| 366 |
asyncio.run(self._test_shutdown_error(secure=False)) |
| 367 |
|
| 368 |
def test_shutdown_error_https(self): |
| 369 |
asyncio.run(self._test_shutdown_error(secure=True)) |
| 370 |
|
| 371 |
def test_stream_lives_until_complete_http(self): |
| 372 |
asyncio.run(self._test_stream_lives_until_complete(secure=False)) |
| 373 |
|
| 374 |
def test_stream_lives_until_complete_https(self): |
| 375 |
asyncio.run(self._test_stream_lives_until_complete(secure=True)) |
| 376 |
|
| 377 |
def test_request_lives_until_stream_complete_http(self): |
| 378 |
asyncio.run(self._test_request_lives_until_stream_complete(secure=False)) |
| 379 |
|
| 380 |
def test_request_lives_until_stream_complete_https(self): |
| 381 |
asyncio.run(self._test_request_lives_until_stream_complete(secure=True)) |
| 382 |
|
| 383 |
def test_h2_client(self): |
| 384 |
asyncio.run(self._test_h2_client()) |
| 385 |
|
| 386 |
def test_h2_manual_write_exception(self): |
| 387 |
asyncio.run(self._test_h2_manual_write_exception()) |
| 388 |
|
| 389 |
@unittest.skipIf(not TlsCipherPref.PQ_DEFAULT.is_supported(), "Cipher pref not supported") |
| 390 |
def test_connect_pq_default(self): |
| 391 |
async def _test(): |
| 392 |
await self._test_connect(secure=True) |
| 393 |
asyncio.run(_test()) |
| 394 |
|
| 395 |
async def _test_cross_thread_http_client(self, secure): |
| 396 |
"""Test using an HTTP client from a different thread/event loop.""" |
| 397 |
self._start_server(secure) |
| 398 |
try: |
| 399 |
|
| 400 |
connection = await self._new_client_connection(secure) |
| 401 |
self.assertTrue(connection.is_open()) |
| 402 |
|
| 403 |
|
| 404 |
async def thread_func(conn): |
| 405 |
|
| 406 |
test_asset_path = 'test/test_aiohttp_client.py' |
| 407 |
request = HttpRequest('GET', '/' + test_asset_path) |
| 408 |
|
| 409 |
|
| 410 |
thread_loop = asyncio.get_event_loop() |
| 411 |
stream = conn.request(request, loop=thread_loop) |
| 412 |
|
| 413 |
|
| 414 |
response = Response() |
| 415 |
status_code = await response.collect_response(stream) |
| 416 |
|
| 417 |
|
| 418 |
assert status_code == 200 |
| 419 |
|
| 420 |
with open(test_asset_path, 'rb') as test_asset: |
| 421 |
test_asset_bytes = test_asset.read() |
| 422 |
assert test_asset_bytes == response.body |
| 423 |
|
| 424 |
return True |
| 425 |
|
| 426 |
|
| 427 |
with concurrent.futures.ThreadPoolExecutor() as executor: |
| 428 |
future = executor.submit( |
| 429 |
lambda: asyncio.run(thread_func(connection)) |
| 430 |
) |
| 431 |
result = future.result() |
| 432 |
self.assertTrue(result) |
| 433 |
|
| 434 |
await connection.close() |
| 435 |
|
| 436 |
finally: |
| 437 |
self._stop_server() |
| 438 |
|
| 439 |
async def _test_cross_thread_http2_client(self): |
| 440 |
"""Test using an HTTP/2 client from a different thread/event loop.""" |
| 441 |
url = urlparse("https://d1cz66xoahf9cl.cloudfront.net/http_test_doc.txt") |
| 442 |
connection = await self._new_h2_client_connection(url) |
| 443 |
|
| 444 |
|
| 445 |
self.assertEqual(connection.version, HttpVersion.Http2) |
| 446 |
|
| 447 |
|
| 448 |
async def thread_func(conn): |
| 449 |
request = HttpRequest('GET', url.path) |
| 450 |
request.headers.add('host', url.hostname) |
| 451 |
|
| 452 |
|
| 453 |
thread_loop = asyncio.get_event_loop() |
| 454 |
stream = conn.request(request, loop=thread_loop) |
| 455 |
|
| 456 |
response = Response() |
| 457 |
status_code = await response.collect_response(stream) |
| 458 |
|
| 459 |
assert status_code == 200 |
| 460 |
return len(response.body) |
| 461 |
|
| 462 |
|
| 463 |
with concurrent.futures.ThreadPoolExecutor() as executor: |
| 464 |
future = executor.submit( |
| 465 |
lambda: asyncio.run(thread_func(connection)) |
| 466 |
) |
| 467 |
body_length = future.result() |
| 468 |
self.assertEqual(14428801, body_length) |
| 469 |
|
| 470 |
await connection.close() |
| 471 |
|
| 472 |
def test_cross_thread_http_client(self): |
| 473 |
asyncio.run(self._test_cross_thread_http_client(secure=False)) |
| 474 |
|
| 475 |
def test_cross_thread_https_client(self): |
| 476 |
asyncio.run(self._test_cross_thread_http_client(secure=True)) |
| 477 |
|
| 478 |
def test_cross_thread_http2_client(self): |
| 479 |
asyncio.run(self._test_cross_thread_http2_client()) |
| 480 |
|
| 481 |
|
| 482 |
class AsyncMockServerTestBase(NativeResourceTest): |
| 483 |
"""Base class for async tests that use the H2 mock server""" |
| 484 |
timeout = 5 |
| 485 |
p_server = None |
| 486 |
mock_server_url = None |
| 487 |
|
| 488 |
def setUp(self): |
| 489 |
super().setUp() |
| 490 |
|
| 491 |
server_path = os.path.join( |
| 492 |
os.path.dirname(__file__), |
| 493 |
'..', |
| 494 |
'crt', |
| 495 |
'aws-c-http', |
| 496 |
'tests', |
| 497 |
'mock_server', |
| 498 |
'h2tls_mock_server.py') |
| 499 |
python_path = sys.executable |
| 500 |
self.mock_server_url = urlparse("https://localhost:3443/echo") |
| 501 |
self.p_server = subprocess.Popen([python_path, server_path]) |
| 502 |
|
| 503 |
self._wait_for_server_ready() |
| 504 |
|
| 505 |
def _wait_for_server_ready(self): |
| 506 |
"""Wait until server is accepting connections.""" |
| 507 |
max_attempts = 20 |
| 508 |
for attempt in range(max_attempts): |
| 509 |
try: |
| 510 |
with socket.create_connection(("127.0.0.1", self.mock_server_url.port), timeout=1): |
| 511 |
return |
| 512 |
except (ConnectionRefusedError, socket.timeout): |
| 513 |
time.sleep(0.5) |
| 514 |
|
| 515 |
|
| 516 |
stdout, stderr = self.p_server.communicate(timeout=0.5) |
| 517 |
raise RuntimeError(f"Server failed to start after {max_attempts} attempts.\n" |
| 518 |
f"STDOUT: {stdout.decode()}\nSTDERR: {stderr.decode()}") |
| 519 |
|
| 520 |
def tearDown(self): |
| 521 |
self.p_server.terminate() |
| 522 |
try: |
| 523 |
self.p_server.wait(timeout=5) |
| 524 |
except subprocess.TimeoutExpired: |
| 525 |
self.p_server.kill() |
| 526 |
super().tearDown() |
| 527 |
|
| 528 |
async def _new_mock_h2_connection( |
| 529 |
self, |
| 530 |
manual_window_management=False, |
| 531 |
initial_window_size=None, |
| 532 |
initial_settings=None): |
| 533 |
"""Create HTTP/2 async client connection to local mock server""" |
| 534 |
event_loop_group = EventLoopGroup() |
| 535 |
host_resolver = DefaultHostResolver(event_loop_group) |
| 536 |
bootstrap = ClientBootstrap(event_loop_group, host_resolver) |
| 537 |
|
| 538 |
port = self.mock_server_url.port |
| 539 |
if port is None: |
| 540 |
port = 443 |
| 541 |
|
| 542 |
tls_ctx_options = TlsContextOptions() |
| 543 |
tls_ctx_options.verify_peer = False |
| 544 |
tls_ctx = ClientTlsContext(tls_ctx_options) |
| 545 |
tls_conn_opt = tls_ctx.new_connection_options() |
| 546 |
tls_conn_opt.set_server_name(self.mock_server_url.hostname) |
| 547 |
tls_conn_opt.set_alpn_list(["h2"]) |
| 548 |
|
| 549 |
if initial_settings is None: |
| 550 |
initial_settings = [Http2Setting(Http2SettingID.ENABLE_PUSH, 0)] |
| 551 |
|
| 552 |
kwargs = { |
| 553 |
'host_name': self.mock_server_url.hostname, |
| 554 |
'port': port, |
| 555 |
'bootstrap': bootstrap, |
| 556 |
'tls_connection_options': tls_conn_opt, |
| 557 |
'initial_settings': initial_settings, |
| 558 |
'manual_window_management': manual_window_management |
| 559 |
} |
| 560 |
if initial_window_size is not None: |
| 561 |
kwargs['initial_window_size'] = initial_window_size |
| 562 |
|
| 563 |
return await AIOHttp2ClientConnection.new(**kwargs) |
| 564 |
|
| 565 |
|
| 566 |
@unittest.skipUnless(os.environ.get('AWS_TEST_LOCALHOST'), 'set env var to run test: AWS_TEST_LOCALHOST') |
| 567 |
class TestAsyncClientMockServer(AsyncMockServerTestBase): |
| 568 |
|
| 569 |
def _on_remote_settings_changed(self, settings): |
| 570 |
|
| 571 |
|
| 572 |
|
| 573 |
|
| 574 |
|
| 575 |
self.assertEqual(len(settings), 3) |
| 576 |
for i in settings: |
| 577 |
if i.id == Http2SettingID.ENABLE_PUSH: |
| 578 |
self.assertEqual(i.value, 0) |
| 579 |
if i.id == Http2SettingID.MAX_CONCURRENT_STREAMS: |
| 580 |
self.assertEqual(i.value, 100) |
| 581 |
if i.id == Http2SettingID.MAX_HEADER_LIST_SIZE: |
| 582 |
self.assertEqual(i.value, 2**16) |
| 583 |
|
| 584 |
async def _new_mock_connection(self, initial_settings=None): |
| 585 |
event_loop_group = EventLoopGroup() |
| 586 |
host_resolver = DefaultHostResolver(event_loop_group) |
| 587 |
bootstrap = ClientBootstrap(event_loop_group, host_resolver) |
| 588 |
|
| 589 |
port = self.mock_server_url.port |
| 590 |
|
| 591 |
if port is None: |
| 592 |
port = 443 |
| 593 |
tls_ctx_options = TlsContextOptions() |
| 594 |
tls_ctx_options.verify_peer = False |
| 595 |
tls_ctx = ClientTlsContext(tls_ctx_options) |
| 596 |
tls_conn_opt = tls_ctx.new_connection_options() |
| 597 |
tls_conn_opt.set_server_name(self.mock_server_url.hostname) |
| 598 |
tls_conn_opt.set_alpn_list(["h2"]) |
| 599 |
|
| 600 |
if initial_settings is None: |
| 601 |
initial_settings = [Http2Setting(Http2SettingID.ENABLE_PUSH, 0)] |
| 602 |
|
| 603 |
connection = await AIOHttp2ClientConnection.new( |
| 604 |
host_name=self.mock_server_url.hostname, |
| 605 |
port=port, |
| 606 |
bootstrap=bootstrap, |
| 607 |
tls_connection_options=tls_conn_opt, |
| 608 |
initial_settings=initial_settings, |
| 609 |
on_remote_settings_changed=self._on_remote_settings_changed) |
| 610 |
|
| 611 |
return connection |
| 612 |
|
| 613 |
async def _test_h2_mock_server_manual_write(self): |
| 614 |
connection = await self._new_mock_connection() |
| 615 |
|
| 616 |
self.assertEqual(connection.version, HttpVersion.Http2) |
| 617 |
|
| 618 |
request = HttpRequest('POST', self.mock_server_url.path) |
| 619 |
request.headers.add('host', self.mock_server_url.hostname) |
| 620 |
|
| 621 |
|
| 622 |
body_chunks = [b'hello', b'he123123', b'', b'hello'] |
| 623 |
total_length = 0 |
| 624 |
content = b'' |
| 625 |
for i in body_chunks: |
| 626 |
total_length = total_length + len(i) |
| 627 |
content += i |
| 628 |
|
| 629 |
async def body_generator(): |
| 630 |
for i in body_chunks: |
| 631 |
yield i |
| 632 |
|
| 633 |
stream = connection.request(request, request_body_generator=body_generator()) |
| 634 |
|
| 635 |
|
| 636 |
response = Response() |
| 637 |
status_code = await response.collect_response(stream) |
| 638 |
|
| 639 |
|
| 640 |
self.assertEqual(200, status_code) |
| 641 |
self.assertEqual(200, response.status_code) |
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
|
| 647 |
parsed_response = json.loads(response.body.decode()) |
| 648 |
self.assertEqual(total_length, int(parsed_response["bytes"])) |
| 649 |
self.assertEqual(content.decode(), parsed_response["body"]) |
| 650 |
await connection.close() |
| 651 |
|
| 652 |
class DelayStream: |
| 653 |
def __init__(self, bad_read=False): |
| 654 |
self._read = False |
| 655 |
self.bad_read = bad_read |
| 656 |
|
| 657 |
def read(self, _len): |
| 658 |
if self.bad_read: |
| 659 |
|
| 660 |
|
| 661 |
raise RuntimeError("bad read exception") |
| 662 |
if self._read: |
| 663 |
|
| 664 |
return b'' |
| 665 |
else: |
| 666 |
self._read = True |
| 667 |
return b'hello' |
| 668 |
|
| 669 |
async def _test_h2_mock_server_settings(self): |
| 670 |
|
| 671 |
exception = None |
| 672 |
try: |
| 673 |
|
| 674 |
initial_settings = [100] |
| 675 |
await self._new_mock_connection(initial_settings) |
| 676 |
except Exception as e: |
| 677 |
exception = e |
| 678 |
self.assertIsNotNone(exception) |
| 679 |
|
| 680 |
|
| 681 |
connection = await self._new_mock_connection() |
| 682 |
self.assertEqual(connection.version, HttpVersion.Http2) |
| 683 |
|
| 684 |
request = HttpRequest('POST', self.mock_server_url.path) |
| 685 |
request.headers.add('host', self.mock_server_url.hostname) |
| 686 |
|
| 687 |
|
| 688 |
async def body_generator(): |
| 689 |
yield b'hello' |
| 690 |
|
| 691 |
stream = connection.request(request, request_body_generator=body_generator()) |
| 692 |
|
| 693 |
response = Response() |
| 694 |
status_code = await response.collect_response(stream) |
| 695 |
|
| 696 |
self.assertEqual(200, status_code) |
| 697 |
self.assertEqual(200, response.status_code) |
| 698 |
|
| 699 |
await connection.close() |
| 700 |
|
| 701 |
def test_h2_mock_server_manual_write(self): |
| 702 |
asyncio.run(self._test_h2_mock_server_manual_write()) |
| 703 |
|
| 704 |
def test_h2_mock_server_settings(self): |
| 705 |
asyncio.run(self._test_h2_mock_server_settings()) |
| 706 |
|
| 707 |
|
| 708 |
class AIOFlowControlTest(AsyncLocalServerTestBase): |
| 709 |
"""HTTP/1.1 async flow control tests using local server""" |
| 710 |
timeout = 10.0 |
| 711 |
|
| 712 |
async def _new_h1_client_connection( |
| 713 |
self, |
| 714 |
secure, |
| 715 |
manual_window_management=False, |
| 716 |
initial_window_size=None, |
| 717 |
read_buffer_capacity=None): |
| 718 |
"""Create HTTP/1.1 async client connection to local server""" |
| 719 |
if secure: |
| 720 |
tls_ctx_opt = TlsContextOptions() |
| 721 |
tls_ctx_opt.verify_peer = False |
| 722 |
tls_ctx = ClientTlsContext(tls_ctx_opt) |
| 723 |
tls_conn_opt = tls_ctx.new_connection_options() |
| 724 |
tls_conn_opt.set_server_name(self.hostname) |
| 725 |
else: |
| 726 |
tls_conn_opt = None |
| 727 |
|
| 728 |
event_loop_group = EventLoopGroup() |
| 729 |
host_resolver = DefaultHostResolver(event_loop_group) |
| 730 |
bootstrap = ClientBootstrap(event_loop_group, host_resolver) |
| 731 |
|
| 732 |
kwargs = { |
| 733 |
'host_name': self.hostname, |
| 734 |
'port': self.port, |
| 735 |
'bootstrap': bootstrap, |
| 736 |
'tls_connection_options': tls_conn_opt, |
| 737 |
'manual_window_management': manual_window_management |
| 738 |
} |
| 739 |
if initial_window_size is not None: |
| 740 |
kwargs['initial_window_size'] = initial_window_size |
| 741 |
if read_buffer_capacity is not None: |
| 742 |
kwargs['read_buffer_capacity'] = read_buffer_capacity |
| 743 |
|
| 744 |
return await AIOHttpClientConnection.new(**kwargs) |
| 745 |
|
| 746 |
async def _test_h1_manual_window_management_happy_path(self): |
| 747 |
"""Test HTTP/1.1 manual window management happy path""" |
| 748 |
self._start_server(secure=True) |
| 749 |
try: |
| 750 |
connection = await self._new_h1_client_connection( |
| 751 |
secure=True, |
| 752 |
manual_window_management=True, |
| 753 |
initial_window_size=5, |
| 754 |
read_buffer_capacity=1000 |
| 755 |
) |
| 756 |
|
| 757 |
|
| 758 |
test_data = b'0123456789' |
| 759 |
test_file_path = 'test_aio_flow_control_data.txt' |
| 760 |
with open(test_file_path, 'wb') as f: |
| 761 |
f.write(test_data) |
| 762 |
|
| 763 |
try: |
| 764 |
request = HttpRequest('GET', '/' + test_file_path) |
| 765 |
request.headers.add('host', self.hostname) |
| 766 |
stream = connection.request(request) |
| 767 |
|
| 768 |
chunks_received = [] |
| 769 |
body = bytearray() |
| 770 |
|
| 771 |
await stream.get_response_status_code() |
| 772 |
while True: |
| 773 |
chunk = await stream.get_next_response_chunk() |
| 774 |
if not chunk: |
| 775 |
break |
| 776 |
chunks_received.append(len(chunk)) |
| 777 |
body.extend(chunk) |
| 778 |
stream.update_window(len(chunk)) |
| 779 |
|
| 780 |
self.assertEqual(test_data, bytes(body)) |
| 781 |
self.assertGreater(len(chunks_received), 0, "No data chunks received") |
| 782 |
|
| 783 |
await connection.close() |
| 784 |
finally: |
| 785 |
|
| 786 |
if os.path.exists(test_file_path): |
| 787 |
os.remove(test_file_path) |
| 788 |
finally: |
| 789 |
self._stop_server() |
| 790 |
|
| 791 |
def test_h1_manual_window_management_happy_path(self): |
| 792 |
asyncio.run(self._test_h1_manual_window_management_happy_path()) |
| 793 |
|
| 794 |
async def _test_h1_stream_flow_control_blocks_and_resumes(self): |
| 795 |
"""Test that HTTP/1.1 stream flow control actually blocks and resumes""" |
| 796 |
self._start_server(secure=True) |
| 797 |
try: |
| 798 |
connection = await self._new_h1_client_connection( |
| 799 |
secure=True, |
| 800 |
manual_window_management=True, |
| 801 |
initial_window_size=1, |
| 802 |
read_buffer_capacity=1000 |
| 803 |
) |
| 804 |
|
| 805 |
|
| 806 |
test_data = bytes(range(100)) |
| 807 |
test_file_path = 'test_aio_flow_control_100.txt' |
| 808 |
with open(test_file_path, 'wb') as f: |
| 809 |
f.write(test_data) |
| 810 |
|
| 811 |
try: |
| 812 |
request = HttpRequest('GET', '/' + test_file_path) |
| 813 |
request.headers.add('host', self.hostname) |
| 814 |
stream = connection.request(request) |
| 815 |
|
| 816 |
chunks_received = [] |
| 817 |
body = bytearray() |
| 818 |
|
| 819 |
await stream.get_response_status_code() |
| 820 |
while True: |
| 821 |
chunk = await stream.get_next_response_chunk() |
| 822 |
if not chunk: |
| 823 |
break |
| 824 |
chunks_received.append(len(chunk)) |
| 825 |
body.extend(chunk) |
| 826 |
stream.update_window(len(chunk)) |
| 827 |
|
| 828 |
self.assertEqual(test_data, bytes(body)) |
| 829 |
|
| 830 |
self.assertGreater(len(chunks_received), 1, "Should receive multiple chunks with tiny window") |
| 831 |
|
| 832 |
await connection.close() |
| 833 |
finally: |
| 834 |
|
| 835 |
if os.path.exists(test_file_path): |
| 836 |
os.remove(test_file_path) |
| 837 |
finally: |
| 838 |
self._stop_server() |
| 839 |
|
| 840 |
def test_h1_stream_flow_control_blocks_and_resumes(self): |
| 841 |
asyncio.run(self._test_h1_stream_flow_control_blocks_and_resumes()) |
| 842 |
|
| 843 |
|
| 844 |
@unittest.skipUnless(os.environ.get('AWS_TEST_LOCALHOST'), 'set env var to run test: AWS_TEST_LOCALHOST') |
| 845 |
class AIOFlowControlH2Test(AsyncMockServerTestBase): |
| 846 |
"""HTTP/2 async flow control tests using local mock server""" |
| 847 |
timeout = 10.0 |
| 848 |
|
| 849 |
async def _test_h2_manual_window_management_happy_path(self): |
| 850 |
"""Test HTTP/2 manual window management happy path""" |
| 851 |
connection = await self._new_mock_h2_connection( |
| 852 |
manual_window_management=True, |
| 853 |
initial_window_size=65536 |
| 854 |
) |
| 855 |
|
| 856 |
|
| 857 |
request = HttpRequest('GET', self.mock_server_url.path) |
| 858 |
request.headers.add('host', self.mock_server_url.hostname) |
| 859 |
request.headers.add('x-repeat-data', '100') |
| 860 |
|
| 861 |
stream = connection.request(request) |
| 862 |
|
| 863 |
chunks_received = [] |
| 864 |
body = bytearray() |
| 865 |
|
| 866 |
await stream.get_response_status_code() |
| 867 |
while True: |
| 868 |
chunk = await stream.get_next_response_chunk() |
| 869 |
if not chunk: |
| 870 |
break |
| 871 |
chunks_received.append(len(chunk)) |
| 872 |
body.extend(chunk) |
| 873 |
stream.update_window(len(chunk)) |
| 874 |
|
| 875 |
self.assertGreater(len(body), 0, "No response body received") |
| 876 |
self.assertGreater(len(chunks_received), 0, "No data chunks received") |
| 877 |
|
| 878 |
await connection.close() |
| 879 |
|
| 880 |
def test_h2_manual_window_management_happy_path(self): |
| 881 |
asyncio.run(self._test_h2_manual_window_management_happy_path()) |
| 882 |
|
| 883 |
async def _test_h2_stream_flow_control_blocks_and_resumes(self): |
| 884 |
"""Test that HTTP/2 stream flow control actually blocks and resumes""" |
| 885 |
connection = await self._new_mock_h2_connection( |
| 886 |
manual_window_management=True, |
| 887 |
initial_window_size=10 |
| 888 |
) |
| 889 |
|
| 890 |
|
| 891 |
request = HttpRequest('GET', self.mock_server_url.path) |
| 892 |
request.headers.add('host', self.mock_server_url.hostname) |
| 893 |
request.headers.add('x-repeat-data', '100') |
| 894 |
|
| 895 |
stream = connection.request(request) |
| 896 |
|
| 897 |
chunks_received = [] |
| 898 |
body = bytearray() |
| 899 |
|
| 900 |
await stream.get_response_status_code() |
| 901 |
while True: |
| 902 |
chunk = await stream.get_next_response_chunk() |
| 903 |
if not chunk: |
| 904 |
break |
| 905 |
chunks_received.append(len(chunk)) |
| 906 |
body.extend(chunk) |
| 907 |
stream.update_window(len(chunk)) |
| 908 |
|
| 909 |
self.assertGreater(len(body), 0, "No response body received") |
| 910 |
|
| 911 |
self.assertGreater(len(chunks_received), 1, "Should receive multiple chunks with small window") |
| 912 |
|
| 913 |
await connection.close() |
| 914 |
|
| 915 |
def test_h2_stream_flow_control_blocks_and_resumes(self): |
| 916 |
asyncio.run(self._test_h2_stream_flow_control_blocks_and_resumes()) |
| 917 |
|
| 918 |
|
| 919 |
class AIOHttp2RemoteEndStreamTest(NativeResourceTest): |
| 920 |
"""Test suite for HTTP/2 on_h2_remote_end_stream callback in asyncio""" |
| 921 |
timeout = 10.0 |
| 922 |
|
| 923 |
async def _new_httpbin_h2_connection(self): |
| 924 |
"""Create HTTP/2 connection to httpbin.org""" |
| 925 |
event_loop_group = EventLoopGroup() |
| 926 |
host_resolver = DefaultHostResolver(event_loop_group) |
| 927 |
bootstrap = ClientBootstrap(event_loop_group, host_resolver) |
| 928 |
|
| 929 |
tls_ctx_options = TlsContextOptions() |
| 930 |
tls_ctx = ClientTlsContext(tls_ctx_options) |
| 931 |
tls_conn_opt = tls_ctx.new_connection_options() |
| 932 |
tls_conn_opt.set_server_name("httpbin.org") |
| 933 |
tls_conn_opt.set_alpn_list(["h2"]) |
| 934 |
|
| 935 |
connection = await AIOHttp2ClientConnection.new( |
| 936 |
host_name="httpbin.org", |
| 937 |
port=443, |
| 938 |
bootstrap=bootstrap, |
| 939 |
tls_connection_options=tls_conn_opt) |
| 940 |
|
| 941 |
return connection |
| 942 |
|
| 943 |
async def _test_h2_remote_end_stream_ordering(self): |
| 944 |
"""Test that on_h2_remote_end_stream fires before on_complete when server finishes first""" |
| 945 |
connection = await self._new_httpbin_h2_connection() |
| 946 |
|
| 947 |
|
| 948 |
request = HttpRequest('POST', '/this-path-does-not-exist-deliberately-404') |
| 949 |
request.headers.add('host', 'httpbin.org') |
| 950 |
|
| 951 |
complete_success = asyncio.Event() |
| 952 |
remote_finished = asyncio.Event() |
| 953 |
complete_fired = asyncio.Event() |
| 954 |
|
| 955 |
async def slow_body_generator(): |
| 956 |
|
| 957 |
yield b'chunk1' |
| 958 |
|
| 959 |
await remote_finished.wait() |
| 960 |
if not complete_fired.is_set(): |
| 961 |
|
| 962 |
complete_success.set() |
| 963 |
|
| 964 |
yield b'chunk2' |
| 965 |
|
| 966 |
stream = connection.request(request, request_body_generator=slow_body_generator()) |
| 967 |
|
| 968 |
|
| 969 |
status_code = await stream.get_response_status_code() |
| 970 |
self.assertEqual(404, status_code) |
| 971 |
|
| 972 |
|
| 973 |
while True: |
| 974 |
chunk = await stream.get_next_response_chunk() |
| 975 |
if not chunk: |
| 976 |
break |
| 977 |
|
| 978 |
|
| 979 |
remote_finished.set() |
| 980 |
|
| 981 |
|
| 982 |
await stream.wait_for_completion() |
| 983 |
complete_fired.set() |
| 984 |
|
| 985 |
self.assertTrue(complete_success.is_set()) |
| 986 |
|
| 987 |
await connection.close() |
| 988 |
|
| 989 |
def test_h2_remote_end_stream_ordering(self): |
| 990 |
"""Test callback ordering with early server response""" |
| 991 |
asyncio.run(self._test_h2_remote_end_stream_ordering()) |
| 992 |
|
| 993 |
|
| 994 |
if __name__ == '__main__': |
| 995 |
unittest.main() |