1 """Utilities to help with aiohttp."""
3 from __future__
import annotations
5 from http
import HTTPStatus
8 from urllib.parse
import parse_qsl
10 from aiohttp
import payload, web
11 from aiohttp.typedefs
import JSONDecoder
12 from multidict
import CIMultiDict, MultiDict
14 from .json
import json_loads
18 """Small mock to imitate stream reader."""
21 """Initialize mock stream reader."""
24 async
def read(self, byte_count: int = -1) -> bytes:
32 """Small mock to imitate payload writer."""
35 """Enable chunking."""
45 """Mock an aiohttp request."""
47 mock_source: str |
None =
None
54 status: int = HTTPStatus.OK,
55 headers: dict[str, str] |
None =
None,
56 query_string: str |
None =
None,
59 """Initialize a request."""
63 self.headers: CIMultiDict[str] = CIMultiDict(headers
or {})
75 def query(self) -> MultiDict[str]:
76 """Return a dictionary with the query variables."""
77 return MultiDict(parse_qsl(self.
query_stringquery_string, keep_blank_values=
True))
81 """Return the body as text."""
82 return self.
_content_content.decode(
"utf-8")
86 """Return the body as text."""
91 """Return True if request has HTTP BODY, False otherwise."""
92 return bool(self.
_text_text)
94 async
def json(self, loads: JSONDecoder = json_loads) -> Any:
95 """Return the body as JSON."""
96 return loads(self.
_text_text)
98 async
def post(self) -> MultiDict[str]:
99 """Return POST parameters."""
100 return MultiDict(parse_qsl(self.
_text_text, keep_blank_values=
True))
103 """Return the body as text."""
104 return self.
_text_text
108 """Serialize an aiohttp response to a dictionary."""
109 if (body := response.body)
is None:
111 elif isinstance(body, payload.StringPayload):
112 body_decoded = body._value.decode(body.encoding
or "utf-8")
113 elif isinstance(body, bytes):
114 body_decoded = body.decode(response.charset
or "utf-8")
116 raise TypeError(
"Unknown payload encoding")
119 "status": response.status,
120 "body": body_decoded,
121 "headers":
dict(response.headers),
None write_headers(self, *Any args, **Any kwargs)
None enable_chunking(self)
MultiDict[str] query(self)
MockStreamReader content(self)
Any json(self, JSONDecoder loads=json_loads)
None _prepare_hook(self, Any response)
None __init__(self, bytes content, str mock_source, str method="GET", int status=HTTPStatus.OK, dict[str, str]|None headers=None, str|None query_string=None, str url="")
MultiDict[str] post(self)
bytes read(self, int byte_count=-1)
None __init__(self, bytes content)
dict[str, Any] serialize_response(web.Response response)