Debian Codegraph @

src/quart_trio/testing/connections.py

raw
1 from __future__ import annotations
2
3 from types import TracebackType
4 from typing import Any, Awaitable, List, Optional, Tuple, Union
5
6 import trio
7 from hypercorn.typing import HTTPScope, WebsocketScope
8 from quart.app import Quart
9 from quart.json import dumps, loads
10 from quart.testing.connections import WebsocketResponseError
11 from quart.typing import TestHTTPConnectionProtocol, TestWebsocketConnectionProtocol
12 from quart.utils import decode_headers
13 from quart.wrappers import Response
14 from quart.wrappers.base import ClientDisconnectedError
15 from werkzeug.datastructures import Headers
16
17
18 class TestHTTPConnection:
19 def __init__(self, app: Quart, scope: HTTPScope, _preserve_context: bool = False) -> None:
20 self.app = app
21 self.headers: Optional[Headers] = None
22 self.push_promises: List[Tuple[str, Headers]] = []
23 self.response_data = bytearray()
24 self.scope = scope
25 self.status_code: Optional[int] = None
26 self._preserve_context = _preserve_context
27 self._server_send, self._server_receive = trio.open_memory_channel[dict](10)
28 self._client_send, self._client_receive = trio.open_memory_channel[Union[bytes, Exception]](
29 10
30 )
31
32 async def send(self, data: bytes) -> None:
33 await self._server_send.send({"type": "http.request", "body": data, "more_body": True})
34
35 async def send_complete(self) -> None:
36 await self._server_send.send({"type": "http.request", "body": b"", "more_body": False})
37
38 async def receive(self) -> bytes:
39 data = await self._client_receive.receive()
40 if isinstance(data, Exception):
41 raise data
42 else:
43 return data
44
45 async def disconnect(self) -> None:
46 await self._server_send.send({"type": "http.disconnect"})
47 await self._server_send.aclose()
48
49 async def __aenter__(self) -> TestHTTPConnectionProtocol:
50 self._nursery_manager = trio.open_nursery()
51 nursery = await self._nursery_manager.__aenter__()
52 nursery.start_soon(self.app, self.scope, self._asgi_receive, self._asgi_send) # type: ignore # noqa: E501
53 return self
54
55 async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
56 if exc_type is not None:
57 await self.disconnect()
58 await self._nursery_manager.__aexit__(exc_type, exc_value, tb)
59 try:
60 async with self._client_receive:
61 async for data in self._client_receive:
62 if isinstance(data, bytes):
63 self.response_data.extend(data)
64 else:
65 raise data
66 except trio.ClosedResourceError:
67 pass
68
69 async def as_response(self) -> Response:
70 try:
71 async with self._client_receive:
72 async for data in self._client_receive:
73 if isinstance(data, bytes):
74 self.response_data.extend(data)
75 except trio.ClosedResourceError:
76 pass
77 return self.app.response_class(bytes(self.response_data), self.status_code, self.headers)
78
79 async def _asgi_receive(self) -> dict:
80 return await self._server_receive.receive()
81
82 async def _asgi_send(self, message: dict) -> None:
83 if message["type"] == "http.response.start":
84 self.headers = decode_headers(message["headers"])
85 self.status_code = message["status"]
86 elif message["type"] == "http.response.body":
87 await self._client_send.send(message["body"])
88 if not message.get("more_body", False):
89 await self._client_send.aclose()
90 elif message["type"] == "http.response.push":
91 self.push_promises.append((message["path"], decode_headers(message["headers"])))
92
93
94 class TestWebsocketConnection:
95 def __init__(self, app: Quart, scope: WebsocketScope) -> None:
96 self.accepted = False
97 self.app = app
98 self.headers: Optional[Headers] = None
99 self.response_data = bytearray()
100 self.scope = scope
101 self.status_code: Optional[int] = None
102 self._server_send, self._server_receive = trio.open_memory_channel[dict](10)
103 self._client_send, self._client_receive = trio.open_memory_channel[
104 Union[bytes, str, Exception]
105 ](10)
106 self._task: Awaitable[None] = None
107
108 async def __aenter__(self) -> TestWebsocketConnectionProtocol:
109 self._nursery_manager = trio.open_nursery()
110 nursery = await self._nursery_manager.__aenter__()
111 nursery.start_soon(self.app, self.scope, self._asgi_receive, self._asgi_send) # type: ignore # noqa: E501
112 return self
113
114 async def __aexit__(self, exc_type: type, exc_value: BaseException, tb: TracebackType) -> None:
115 await self.disconnect()
116 await self._nursery_manager.__aexit__(exc_type, exc_value, tb)
117
118 async def receive(self) -> str | bytes:
119 data = await self._client_receive.receive()
120 if isinstance(data, Exception):
121 raise data
122 else:
123 return data
124
125 async def send(self, data: str | bytes) -> None:
126 if isinstance(data, str):
127 await self._server_send.send({"type": "websocket.receive", "text": data})
128 else:
129 await self._server_send.send({"type": "websocket.receive", "bytes": data})
130
131 async def receive_json(self) -> Any:
132 data = await self.receive()
133 return loads(data)
134
135 async def send_json(self, data: Any) -> None:
136 raw = dumps(data)
137 await self.send(raw)
138
139 async def close(self, code: int) -> None:
140 await self._server_send.send({"type": "websocket.close", "code": int})
141 await self._server_send.aclose()
142
143 async def disconnect(self) -> None:
144 await self._server_send.send({"type": "websocket.disconnect"})
145 await self._server_send.aclose()
146
147 async def _asgi_receive(self) -> dict:
148 return await self._server_receive.receive()
149
150 async def _asgi_send(self, message: dict) -> None:
151 if message["type"] == "websocket.accept":
152 self.accepted = True
153 elif message["type"] == "websocket.send":
154 await self._client_send.send(message.get("bytes") or message.get("text"))
155 elif message["type"] == "websocket.http.response.start":
156 self.headers = decode_headers(message["headers"])
157 self.status_code = message["status"]
158 elif message["type"] == "websocket.http.response.body":
159 self.response_data.extend(message["body"])
160 if not message.get("more_body", False):
161 await self._client_send.send(
162 WebsocketResponseError(
163 self.app.response_class(
164 bytes(self.response_data), self.status_code, self.headers
165 )
166 )
167 )
168 elif message["type"] == "websocket.close":
169 await self._client_send.send(ClientDisconnectedError(message.get("code", 1000)))
170 await self._client_send.aclose()