Skip to content
Myr

test_http2.py

This file

Path

tests/dispatch/test_http2.py

158 lines · 5.5 KiB · Python

Last changed by

Drop backend parameter on AsyncClient (#791)Florimond Mancabefore adoption5380417

History of this file

Take it

1import json2import socket34import h2.connection5import h2.events6import pytest7from h2.settings import SettingCodes89from httpx import AsyncClient, Response, TimeoutException10from httpx._dispatch.connection_pool import ConnectionPool1112from .utils import MockHTTP2Backend131415async def app(request):16    method = request.method17    path = request.url.path18    body = b"".join([part async for part in request.stream])19    content = json.dumps(20        {"method": method, "path": path, "body": body.decode()}21    ).encode()22    headers = {"Content-Length": str(len(content))}23    return Response(200, headers=headers, content=content, request=request)242526@pytest.mark.asyncio27async def test_http2_get_request():28    backend = MockHTTP2Backend(app=app)29    dispatch = ConnectionPool(backend=backend, http2=True)3031    async with AsyncClient(dispatch=dispatch) as client:32        response = await client.get("http://example.org")3334    assert response.status_code == 20035    assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}363738@pytest.mark.asyncio39async def test_http2_post_request():40    backend = MockHTTP2Backend(app=app)41    dispatch = ConnectionPool(backend=backend, http2=True)4243    async with AsyncClient(dispatch=dispatch) as client:44        response = await client.post("http://example.org", data=b"<data>")4546    assert response.status_code == 20047    assert json.loads(response.content) == {48        "method": "POST",49        "path": "/",50        "body": "<data>",51    }525354@pytest.mark.asyncio55async def test_http2_large_post_request():56    backend = MockHTTP2Backend(app=app)57    dispatch = ConnectionPool(backend=backend, http2=True)5859    data = b"a" * 10000060    async with AsyncClient(dispatch=dispatch) as client:61        response = await client.post("http://example.org", data=data)62    assert response.status_code == 20063    assert json.loads(response.content) == {64        "method": "POST",65        "path": "/",66        "body": data.decode(),67    }686970@pytest.mark.asyncio71async def test_http2_multiple_requests():72    backend = MockHTTP2Backend(app=app)73    dispatch = ConnectionPool(backend=backend, http2=True)7475    async with AsyncClient(dispatch=dispatch) as client:76        response_1 = await client.get("http://example.org/1")77        response_2 = await client.get("http://example.org/2")78        response_3 = await client.get("http://example.org/3")7980    assert response_1.status_code == 20081    assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}8283    assert response_2.status_code == 20084    assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}8586    assert response_3.status_code == 20087    assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}888990@pytest.mark.asyncio91async def test_http2_reconnect():92    """93    If a connection has been dropped between requests, then we should94    be seemlessly reconnected.95    """96    backend = MockHTTP2Backend(app=app)97    dispatch = ConnectionPool(backend=backend, http2=True)9899    async with AsyncClient(dispatch=dispatch) as client:100        response_1 = await client.get("http://example.org/1")101        backend.server.close_connection = True102        response_2 = await client.get("http://example.org/2")103104    assert response_1.status_code == 200105    assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}106107    assert response_2.status_code == 200108    assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}109110111@pytest.mark.asyncio112async def test_http2_settings_in_handshake():113    backend = MockHTTP2Backend(app=app)114    dispatch = ConnectionPool(backend=backend, http2=True)115116    async with AsyncClient(dispatch=dispatch) as client:117        await client.get("http://example.org")118119    h2_conn = backend.server.conn120121    assert isinstance(h2_conn, h2.connection.H2Connection)122    expected_settings = {123        SettingCodes.HEADER_TABLE_SIZE: 4096,124        SettingCodes.ENABLE_PUSH: 0,125        SettingCodes.MAX_CONCURRENT_STREAMS: 100,126        SettingCodes.INITIAL_WINDOW_SIZE: 65535,127        SettingCodes.MAX_FRAME_SIZE: 16384,128        SettingCodes.MAX_HEADER_LIST_SIZE: 65536,129        # This one's here because h2 helpfully populates remote_settings130        # with default values even if the peer doesn't send the setting.131        SettingCodes.ENABLE_CONNECT_PROTOCOL: 0,132    }133    assert dict(h2_conn.remote_settings) == expected_settings134135    # We don't expect the ENABLE_CONNECT_PROTOCOL to be in the handshake136    expected_settings.pop(SettingCodes.ENABLE_CONNECT_PROTOCOL)137138    assert len(backend.server.settings_changed) == 1139    settings = backend.server.settings_changed[0]140141    assert isinstance(settings, h2.events.RemoteSettingsChanged)142    assert len(settings.changed_settings) == len(expected_settings)143    for setting_code, changed_setting in settings.changed_settings.items():144        assert isinstance(changed_setting, h2.settings.ChangedSetting)145        assert changed_setting.new_value == expected_settings[setting_code]146147148@pytest.mark.usefixtures("async_environment")149async def test_http2_live_request():150    async with AsyncClient(http2=True) as client:151        try:152            resp = await client.get("https://nghttp2.org/httpbin/anything")153        except TimeoutException:  # pragma: nocover154            pytest.xfail(reason="nghttp2.org appears to be unresponsive")155        except socket.gaierror:  # pragma: nocover156            pytest.xfail(reason="You appear to be offline")157        assert resp.status_code == 200158        assert resp.http_version == "HTTP/2"