| 1 |
import re |
| 2 |
from http import HTTPStatus |
| 3 |
from types import TracebackType |
| 4 |
from collections import namedtuple |
| 5 |
from unittest import mock |
| 6 |
from urllib.parse import parse_qs |
| 7 |
from yarl import URL |
| 8 |
from orjson import dumps, loads |
| 9 |
from aiohttp import ( |
| 10 |
ClientConnectionError, |
| 11 |
ClientResponseError, |
| 12 |
StreamReader |
| 13 |
) |
| 14 |
from multidict import CIMultiDict |
| 15 |
|
| 16 |
|
| 17 |
RETYPE = type(re.compile("")) |
| 18 |
|
| 19 |
REQUEST_INFO = namedtuple("REQUEST_INFO", ["url", "method", "headers", "real_url"]) |
| 20 |
|
| 21 |
|
| 22 |
def mock_stream(data) -> StreamReader: |
| 23 |
"""Mock a stream with data.""" |
| 24 |
protocol = mock.Mock(_reading_paused=False) |
| 25 |
stream = StreamReader(protocol, limit=2**16) |
| 26 |
stream.feed_data(data) |
| 27 |
stream.feed_eof() |
| 28 |
return stream |
| 29 |
|
| 30 |
|
| 31 |
class AiohttpMockSession: |
| 32 |
"""MockAiohttpsession.""" |
| 33 |
def __init__(self, url, method, response, status, headers=None): |
| 34 |
self.url = URL(url) |
| 35 |
self.method = method |
| 36 |
self.response_bytes = response |
| 37 |
self.status = status |
| 38 |
self._headers = CIMultiDict(headers or {}) |
| 39 |
|
| 40 |
@property |
| 41 |
def headers(self): |
| 42 |
"""Return content_type.""" |
| 43 |
return self._headers |
| 44 |
|
| 45 |
async def __aenter__(self): |
| 46 |
return AiohttpClientMockResponse( |
| 47 |
method=self.method, |
| 48 |
url=self.url, |
| 49 |
status=self.status, |
| 50 |
response=self.response_bytes |
| 51 |
) |
| 52 |
|
| 53 |
async def __aexit__(self, *args): |
| 54 |
pass |
| 55 |
|
| 56 |
|
| 57 |
class AiohttpClientMockResponse: |
| 58 |
"""Mock Aiohttp client response. |
| 59 |
|
| 60 |
Adapted from home-assistant/core/tests/test_util/aiohttp.py |
| 61 |
""" |
| 62 |
def __init__( |
| 63 |
self, |
| 64 |
method, |
| 65 |
url: URL, |
| 66 |
status=HTTPStatus.OK, |
| 67 |
response=None, |
| 68 |
json=None, |
| 69 |
text=None, |
| 70 |
cookies=None, |
| 71 |
exc=None, |
| 72 |
headers=None, |
| 73 |
side_effect=None, |
| 74 |
closing=None, |
| 75 |
) -> None: |
| 76 |
"""Initialize a fake response. |
| 77 |
|
| 78 |
Args: |
| 79 |
method: str: HTTP method |
| 80 |
url: URL: URL of the response |
| 81 |
status: HTTPStatus: HTTP status code |
| 82 |
response: bytes: Response content |
| 83 |
json: dict: JSON response content |
| 84 |
text: str: Text response content |
| 85 |
cookies: dict: Cookies to set |
| 86 |
exc: Exception: Exception to raise |
| 87 |
headers: dict: Headers to set |
| 88 |
side_effect: Exception: Exception to raise when read |
| 89 |
closing: bool: Simulate closing connection |
| 90 |
""" |
| 91 |
if json is not None: |
| 92 |
text = dumps(json) |
| 93 |
if isinstance(text, str): |
| 94 |
response = text.encode("utf-8") |
| 95 |
if response is None: |
| 96 |
response = b"" |
| 97 |
|
| 98 |
self.charset = "utf-8" |
| 99 |
self.method = method |
| 100 |
self._url = url |
| 101 |
self.status = status |
| 102 |
self._response = response |
| 103 |
self.exc = exc |
| 104 |
self.side_effect = side_effect |
| 105 |
self.closing = closing |
| 106 |
self._headers = CIMultiDict(headers or {}) |
| 107 |
self._cookies = {} |
| 108 |
|
| 109 |
if cookies: |
| 110 |
for name, data in cookies.items(): |
| 111 |
cookie = mock.MagicMock() |
| 112 |
cookie.value = data |
| 113 |
self._cookies[name] = cookie |
| 114 |
|
| 115 |
def match_request(self, method, url, params=None): |
| 116 |
"""Test if response answers request.""" |
| 117 |
if method.lower() != self.method.lower(): |
| 118 |
return False |
| 119 |
|
| 120 |
|
| 121 |
if isinstance(self._url, RETYPE): |
| 122 |
return self._url.search(str(url)) is not None |
| 123 |
|
| 124 |
if ( |
| 125 |
self._url.scheme != url.scheme |
| 126 |
or self._url.host != url.host |
| 127 |
or self._url.path != url.path |
| 128 |
): |
| 129 |
return False |
| 130 |
|
| 131 |
|
| 132 |
request_qs = parse_qs(url.query_string) |
| 133 |
matcher_qs = parse_qs(self._url.query_string) |
| 134 |
for key, vals in matcher_qs.items(): |
| 135 |
for val in vals: |
| 136 |
try: |
| 137 |
request_qs.get(key, []).remove(val) |
| 138 |
except ValueError: |
| 139 |
return False |
| 140 |
|
| 141 |
return True |
| 142 |
|
| 143 |
@property |
| 144 |
def request_info(self): |
| 145 |
"""Return request info.""" |
| 146 |
return REQUEST_INFO( |
| 147 |
url=self.url, |
| 148 |
method=self.method, |
| 149 |
headers=self.headers, |
| 150 |
real_url=self.url) |
| 151 |
|
| 152 |
@property |
| 153 |
def headers(self): |
| 154 |
"""Return content_type.""" |
| 155 |
return self._headers |
| 156 |
|
| 157 |
@property |
| 158 |
def cookies(self): |
| 159 |
"""Return dict of cookies.""" |
| 160 |
return self._cookies |
| 161 |
|
| 162 |
@property |
| 163 |
def url(self): |
| 164 |
"""Return yarl of URL.""" |
| 165 |
return self._url |
| 166 |
|
| 167 |
@property |
| 168 |
def content_type(self): |
| 169 |
"""Return yarl of URL.""" |
| 170 |
return self._headers.get("content-type") |
| 171 |
|
| 172 |
@property |
| 173 |
def content(self): |
| 174 |
"""Return content.""" |
| 175 |
return mock_stream(self.response) |
| 176 |
|
| 177 |
async def read(self): |
| 178 |
"""Return mock response.""" |
| 179 |
return self.response |
| 180 |
|
| 181 |
async def text(self, encoding="utf-8", errors="strict"): |
| 182 |
"""Return mock response as a string.""" |
| 183 |
return self.response.decode(encoding, errors=errors) |
| 184 |
|
| 185 |
async def json(self, encoding="utf-8", content_type=None, loads=loads): |
| 186 |
"""Return mock response as a json.""" |
| 187 |
return loads(self.response.decode(encoding)) |
| 188 |
|
| 189 |
def release(self): |
| 190 |
"""Mock release.""" |
| 191 |
|
| 192 |
def raise_for_status(self): |
| 193 |
"""Raise error if status is 400 or higher.""" |
| 194 |
if self.status >= 400: |
| 195 |
request_info = mock.Mock(real_url="http://example.com") |
| 196 |
raise ClientResponseError( |
| 197 |
request_info=request_info, |
| 198 |
history=None, |
| 199 |
status=self.status, |
| 200 |
headers=self.headers, |
| 201 |
) |
| 202 |
|
| 203 |
def close(self): |
| 204 |
"""Mock close.""" |
| 205 |
|
| 206 |
async def wait_for_close(self): |
| 207 |
"""Wait until all requests are done. |
| 208 |
|
| 209 |
Do nothing as we are mocking. |
| 210 |
""" |
| 211 |
|
| 212 |
@property |
| 213 |
def response(self): |
| 214 |
"""Property method to expose the response to other read methods.""" |
| 215 |
if self.closing: |
| 216 |
raise ClientConnectionError("Connection closed") |
| 217 |
return self._response |
| 218 |
|
| 219 |
async def __aenter__(self): |
| 220 |
"""Enter the context manager.""" |
| 221 |
return self |
| 222 |
|
| 223 |
async def __aexit__( |
| 224 |
self, |
| 225 |
exc_type: type[BaseException] | None, |
| 226 |
exc_val: BaseException | None, |
| 227 |
exc_tb: TracebackType | None, |
| 228 |
) -> None: |
| 229 |
"""Exit the context manager.""" |