Skip to content
Myr

test_http2.py

This file

Path

tests/dispatch/test_http2.py

119 lines · 3.9 KiB · Python

Last changed by

Add idna support. More tests.Tom Christiebefore adoptionb948798

History of this file

Take it

1import json23import h2.config4import h2.connection5import h2.events6import pytest78import httpcore91011class MockServer(httpcore.BaseReader, httpcore.BaseWriter):12    """13    This class exposes Reader and Writer style interfaces14    """1516    def __init__(self):17        config = h2.config.H2Configuration(client_side=False)18        self.conn = h2.connection.H2Connection(config=config)19        self.buffer = b""20        self.requests = {}2122    # BaseReader interface2324    async def read(self, n, timeout) -> bytes:25        send, self.buffer = self.buffer[:n], self.buffer[n:]26        return send2728    # BaseWriter interface2930    def write_no_block(self, data: bytes) -> None:31        events = self.conn.receive_data(data)32        self.buffer += self.conn.data_to_send()33        for event in events:34            if isinstance(event, h2.events.RequestReceived):35                self.request_received(event.headers, event.stream_id)36            elif isinstance(event, h2.events.DataReceived):37                self.receive_data(event.data, event.stream_id)38            elif isinstance(event, h2.events.StreamEnded):39                self.stream_complete(event.stream_id)4041    async def write(self, data: bytes, timeout) -> None:42        self.write_no_block(data)4344    async def close(self) -> None:45        pass4647    # Server implementation4849    def request_received(self, headers, stream_id):50        if stream_id not in self.requests:51            self.requests[stream_id] = []52        self.requests[stream_id].append({"headers": headers, "data": b""})5354    def receive_data(self, data, stream_id):55        self.requests[stream_id][-1]["data"] += data5657    def stream_complete(self, stream_id):58        request = self.requests[stream_id].pop(0)59        if not self.requests[stream_id]:60            del self.requests[stream_id]6162        request_headers = dict(request["headers"])63        request_data = request["data"]6465        response_body = json.dumps(66            {67                "method": request_headers[b":method"].decode(),68                "path": request_headers[b":path"].decode(),69                "body": request_data.decode(),70            }71        ).encode()7273        response_headers = (74            (b":status", b"200"),75            (b"content-length", str(len(response_body)).encode()),76        )77        self.conn.send_headers(stream_id, response_headers)78        self.conn.send_data(stream_id, response_body, end_stream=True)79        self.buffer += self.conn.data_to_send()808182@pytest.mark.asyncio83async def test_http2_get_request():84    server = MockServer()85    async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:86        response = await conn.request("GET", "http://example.org")87    assert response.status_code == 20088    assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}899091@pytest.mark.asyncio92async def test_http2_post_request():93    server = MockServer()94    async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:95        response = await conn.request("POST", "http://example.org", content=b"<data>")96    assert response.status_code == 20097    assert json.loads(response.content) == {98        "method": "POST",99        "path": "/",100        "body": "<data>",101    }102103104@pytest.mark.asyncio105async def test_http2_multiple_requests():106    server = MockServer()107    async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:108        response_1 = await conn.request("GET", "http://example.org/1")109        response_2 = await conn.request("GET", "http://example.org/2")110        response_3 = await conn.request("GET", "http://example.org/3")111112    assert response_1.status_code == 200113    assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}114115    assert response_2.status_code == 200116    assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}117118    assert response_3.status_code == 200119    assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}