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 fileTake it
Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 1–72why, one step back1import 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()72Add idna support. More tests.Tom Christiebefore adoptionb948798
lines 73–76why, one step back73 response_headers = (74 (b":status", b"200"),75 (b"content-length", str(len(response_body)).encode()),76 )Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 77–87why, one step back77 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 == 200Response.contentTom Christiebefore adoption4c55113
line 88why, one step back88 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 89–94why, one step back899091@pytest.mark.asyncio92async def test_http2_post_request():93 server = MockServer()94 async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:Prefer 'content' over 'body'Tom Christiebefore adoption4255d41
line 95why, one step back95 response = await conn.request("POST", "http://example.org", content=b"<data>")Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
line 96why, one step back96 assert response.status_code == 200Response.contentTom Christiebefore adoption4c55113
line 97why, one step back97 assert json.loads(response.content) == {Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 98–112why, one step back98 "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 == 200Response.contentTom Christiebefore adoption4c55113
line 113why, one step back113 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 114–115why, one step back114115 assert response_2.status_code == 200Response.contentTom Christiebefore adoption4c55113
line 116why, one step back116 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}Rejig test and tighten up models APITom Christiebefore adoptiondea4d42
lines 117–118why, one step back117118 assert response_3.status_code == 200Response.contentTom Christiebefore adoption4c55113
line 119why, one step back119 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}