2016-10-24 06:48:01 +00:00
|
|
|
"""Aiohttp test utils."""
|
|
|
|
import asyncio
|
|
|
|
from contextlib import contextmanager
|
|
|
|
import json as _json
|
2018-03-04 05:28:04 +00:00
|
|
|
import re
|
2016-10-24 06:48:01 +00:00
|
|
|
from unittest import mock
|
2018-03-04 05:28:04 +00:00
|
|
|
from urllib.parse import parse_qs
|
|
|
|
|
|
|
|
from aiohttp import ClientSession
|
2018-08-10 16:09:42 +00:00
|
|
|
from aiohttp.streams import StreamReader
|
2018-03-04 05:28:04 +00:00
|
|
|
from yarl import URL
|
2016-10-24 06:48:01 +00:00
|
|
|
|
2017-12-31 23:04:49 +00:00
|
|
|
from aiohttp.client_exceptions import ClientResponseError
|
|
|
|
|
2018-08-20 14:34:18 +00:00
|
|
|
from homeassistant.const import EVENT_HOMEASSISTANT_CLOSE
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
retype = type(re.compile(""))
|
2018-07-07 14:48:02 +00:00
|
|
|
|
2016-10-24 06:48:01 +00:00
|
|
|
|
2018-08-10 16:09:42 +00:00
|
|
|
def mock_stream(data):
|
|
|
|
"""Mock a stream with data."""
|
|
|
|
protocol = mock.Mock(_reading_paused=False)
|
|
|
|
stream = StreamReader(protocol)
|
|
|
|
stream.feed_data(data)
|
|
|
|
stream.feed_eof()
|
|
|
|
return stream
|
|
|
|
|
|
|
|
|
2016-10-24 06:48:01 +00:00
|
|
|
class AiohttpClientMocker:
|
|
|
|
"""Mock Aiohttp client requests."""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
"""Initialize the request mocker."""
|
|
|
|
self._mocks = []
|
2017-01-09 16:08:37 +00:00
|
|
|
self._cookies = {}
|
2016-10-24 06:48:01 +00:00
|
|
|
self.mock_calls = []
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
def request(
|
|
|
|
self,
|
|
|
|
method,
|
|
|
|
url,
|
|
|
|
*,
|
|
|
|
auth=None,
|
|
|
|
status=200,
|
|
|
|
text=None,
|
|
|
|
data=None,
|
|
|
|
content=None,
|
|
|
|
json=None,
|
|
|
|
params=None,
|
|
|
|
headers={},
|
|
|
|
exc=None,
|
|
|
|
cookies=None,
|
|
|
|
):
|
2016-10-24 06:48:01 +00:00
|
|
|
"""Mock a request."""
|
2018-03-04 05:28:04 +00:00
|
|
|
if json is not None:
|
2016-10-24 06:48:01 +00:00
|
|
|
text = _json.dumps(json)
|
2018-03-04 05:28:04 +00:00
|
|
|
if text is not None:
|
2019-07-31 19:25:30 +00:00
|
|
|
content = text.encode("utf-8")
|
2016-10-24 06:48:01 +00:00
|
|
|
if content is None:
|
2019-07-31 19:25:30 +00:00
|
|
|
content = b""
|
2018-03-04 05:28:04 +00:00
|
|
|
|
2018-07-07 14:48:02 +00:00
|
|
|
if not isinstance(url, retype):
|
2018-03-04 05:28:04 +00:00
|
|
|
url = URL(url)
|
2016-12-01 06:20:21 +00:00
|
|
|
if params:
|
2018-08-10 16:09:42 +00:00
|
|
|
url = url.with_query(params)
|
2016-12-02 02:30:41 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
self._mocks.append(
|
|
|
|
AiohttpClientMockResponse(
|
|
|
|
method, url, status, content, cookies, exc, headers
|
|
|
|
)
|
|
|
|
)
|
2016-10-24 06:48:01 +00:00
|
|
|
|
|
|
|
def get(self, *args, **kwargs):
|
|
|
|
"""Register a mock get request."""
|
2019-07-31 19:25:30 +00:00
|
|
|
self.request("get", *args, **kwargs)
|
2016-10-24 06:48:01 +00:00
|
|
|
|
|
|
|
def put(self, *args, **kwargs):
|
|
|
|
"""Register a mock put request."""
|
2019-07-31 19:25:30 +00:00
|
|
|
self.request("put", *args, **kwargs)
|
2016-10-24 06:48:01 +00:00
|
|
|
|
|
|
|
def post(self, *args, **kwargs):
|
|
|
|
"""Register a mock post request."""
|
2019-07-31 19:25:30 +00:00
|
|
|
self.request("post", *args, **kwargs)
|
2016-10-24 06:48:01 +00:00
|
|
|
|
|
|
|
def delete(self, *args, **kwargs):
|
|
|
|
"""Register a mock delete request."""
|
2019-07-31 19:25:30 +00:00
|
|
|
self.request("delete", *args, **kwargs)
|
2016-10-24 06:48:01 +00:00
|
|
|
|
|
|
|
def options(self, *args, **kwargs):
|
|
|
|
"""Register a mock options request."""
|
2019-07-31 19:25:30 +00:00
|
|
|
self.request("options", *args, **kwargs)
|
2016-10-24 06:48:01 +00:00
|
|
|
|
2019-04-15 22:27:13 +00:00
|
|
|
def patch(self, *args, **kwargs):
|
|
|
|
"""Register a mock patch request."""
|
2019-07-31 19:25:30 +00:00
|
|
|
self.request("patch", *args, **kwargs)
|
2019-04-15 22:27:13 +00:00
|
|
|
|
2016-10-24 06:48:01 +00:00
|
|
|
@property
|
|
|
|
def call_count(self):
|
2017-05-02 16:18:47 +00:00
|
|
|
"""Return the number of requests made."""
|
2016-10-24 06:48:01 +00:00
|
|
|
return len(self.mock_calls)
|
|
|
|
|
2017-01-09 16:08:37 +00:00
|
|
|
def clear_requests(self):
|
|
|
|
"""Reset mock calls."""
|
|
|
|
self._mocks.clear()
|
|
|
|
self._cookies.clear()
|
|
|
|
self.mock_calls.clear()
|
|
|
|
|
2018-03-04 05:28:04 +00:00
|
|
|
def create_session(self, loop):
|
|
|
|
"""Create a ClientSession that is bound to this mocker."""
|
|
|
|
session = ClientSession(loop=loop)
|
2018-03-15 20:49:49 +00:00
|
|
|
# Setting directly on `session` will raise deprecation warning
|
2019-07-31 19:25:30 +00:00
|
|
|
object.__setattr__(session, "_request", self.match_request)
|
2018-03-04 05:28:04 +00:00
|
|
|
return session
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
async def match_request(
|
|
|
|
self,
|
|
|
|
method,
|
|
|
|
url,
|
|
|
|
*,
|
|
|
|
data=None,
|
|
|
|
auth=None,
|
|
|
|
params=None,
|
|
|
|
headers=None,
|
|
|
|
allow_redirects=None,
|
|
|
|
timeout=None,
|
|
|
|
json=None,
|
|
|
|
cookies=None,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2016-10-24 06:48:01 +00:00
|
|
|
"""Match a request against pre-registered requests."""
|
2017-04-07 05:19:08 +00:00
|
|
|
data = data or json
|
2018-03-04 05:28:04 +00:00
|
|
|
url = URL(url)
|
|
|
|
if params:
|
|
|
|
url = url.with_query(params)
|
|
|
|
|
2016-10-24 06:48:01 +00:00
|
|
|
for response in self._mocks:
|
2016-12-01 06:20:21 +00:00
|
|
|
if response.match_request(method, url, params):
|
2018-01-10 18:48:31 +00:00
|
|
|
self.mock_calls.append((method, url, data, headers))
|
2016-12-02 02:30:41 +00:00
|
|
|
|
2017-01-09 16:08:37 +00:00
|
|
|
if response.exc:
|
|
|
|
raise response.exc
|
2016-10-24 06:48:01 +00:00
|
|
|
return response
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
assert False, "No mock registered for {} {} {}".format(
|
|
|
|
method.upper(), url, params
|
|
|
|
)
|
2016-10-24 06:48:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
class AiohttpClientMockResponse:
|
|
|
|
"""Mock Aiohttp client response."""
|
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
def __init__(
|
|
|
|
self, method, url, status, response, cookies=None, exc=None, headers=None
|
|
|
|
):
|
2016-10-24 06:48:01 +00:00
|
|
|
"""Initialize a fake response."""
|
|
|
|
self.method = method
|
2016-11-03 02:34:12 +00:00
|
|
|
self._url = url
|
2016-10-24 06:48:01 +00:00
|
|
|
self.status = status
|
|
|
|
self.response = response
|
2017-01-09 16:08:37 +00:00
|
|
|
self.exc = exc
|
2016-10-24 06:48:01 +00:00
|
|
|
|
2018-01-30 22:44:05 +00:00
|
|
|
self._headers = headers or {}
|
2017-01-16 10:06:23 +00:00
|
|
|
self._cookies = {}
|
|
|
|
|
|
|
|
if cookies:
|
|
|
|
for name, data in cookies.items():
|
|
|
|
cookie = mock.MagicMock()
|
|
|
|
cookie.value = data
|
|
|
|
self._cookies[name] = cookie
|
|
|
|
|
2016-12-01 06:20:21 +00:00
|
|
|
def match_request(self, method, url, params=None):
|
2016-10-24 06:48:01 +00:00
|
|
|
"""Test if response answers request."""
|
2016-11-03 02:34:12 +00:00
|
|
|
if method.lower() != self.method.lower():
|
|
|
|
return False
|
|
|
|
|
|
|
|
# regular expression matching
|
2018-07-07 14:48:02 +00:00
|
|
|
if isinstance(self._url, retype):
|
2018-03-04 05:28:04 +00:00
|
|
|
return self._url.search(str(url)) is not None
|
2016-11-03 02:34:12 +00:00
|
|
|
|
2019-07-31 19:25:30 +00:00
|
|
|
if (
|
|
|
|
self._url.scheme != url.scheme
|
|
|
|
or self._url.host != url.host
|
|
|
|
or self._url.path != url.path
|
|
|
|
):
|
2016-11-03 02:34:12 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
# Ensure all query components in matcher are present in the request
|
2018-03-04 05:28:04 +00:00
|
|
|
request_qs = parse_qs(url.query_string)
|
|
|
|
matcher_qs = parse_qs(self._url.query_string)
|
2016-11-03 02:34:12 +00:00
|
|
|
for key, vals in matcher_qs.items():
|
|
|
|
for val in vals:
|
|
|
|
try:
|
|
|
|
request_qs.get(key, []).remove(val)
|
|
|
|
except ValueError:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
2016-10-24 06:48:01 +00:00
|
|
|
|
2017-01-30 00:15:40 +00:00
|
|
|
@property
|
|
|
|
def headers(self):
|
|
|
|
"""Return content_type."""
|
|
|
|
return self._headers
|
|
|
|
|
2017-01-16 10:06:23 +00:00
|
|
|
@property
|
|
|
|
def cookies(self):
|
|
|
|
"""Return dict of cookies."""
|
|
|
|
return self._cookies
|
|
|
|
|
2018-12-06 08:20:53 +00:00
|
|
|
@property
|
|
|
|
def url(self):
|
|
|
|
"""Return yarl of URL."""
|
|
|
|
return self._url
|
|
|
|
|
2018-12-17 10:27:03 +00:00
|
|
|
@property
|
|
|
|
def content_type(self):
|
|
|
|
"""Return yarl of URL."""
|
2019-07-31 19:25:30 +00:00
|
|
|
return self._headers.get("content-type")
|
2018-12-17 10:27:03 +00:00
|
|
|
|
2018-08-10 16:09:42 +00:00
|
|
|
@property
|
|
|
|
def content(self):
|
|
|
|
"""Return content."""
|
|
|
|
return mock_stream(self.response)
|
|
|
|
|
2016-10-24 06:48:01 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def read(self):
|
|
|
|
"""Return mock response."""
|
|
|
|
return self.response
|
|
|
|
|
|
|
|
@asyncio.coroutine
|
2019-07-31 19:25:30 +00:00
|
|
|
def text(self, encoding="utf-8"):
|
2016-10-24 06:48:01 +00:00
|
|
|
"""Return mock response as a string."""
|
|
|
|
return self.response.decode(encoding)
|
|
|
|
|
2017-01-14 07:18:03 +00:00
|
|
|
@asyncio.coroutine
|
2019-07-31 19:25:30 +00:00
|
|
|
def json(self, encoding="utf-8"):
|
2017-01-14 07:18:03 +00:00
|
|
|
"""Return mock response as a json."""
|
|
|
|
return _json.loads(self.response.decode(encoding))
|
|
|
|
|
2016-10-24 06:48:01 +00:00
|
|
|
@asyncio.coroutine
|
|
|
|
def release(self):
|
|
|
|
"""Mock release."""
|
|
|
|
pass
|
|
|
|
|
2017-12-31 23:04:49 +00:00
|
|
|
def raise_for_status(self):
|
|
|
|
"""Raise error if status is 400 or higher."""
|
|
|
|
if self.status >= 400:
|
2019-09-19 18:34:41 +00:00
|
|
|
request_info = mock.Mock(real_url="http://example.com")
|
2017-12-31 23:04:49 +00:00
|
|
|
raise ClientResponseError(
|
2019-09-19 18:34:41 +00:00
|
|
|
request_info=request_info,
|
|
|
|
history=None,
|
|
|
|
code=self.status,
|
|
|
|
headers=self.headers,
|
2019-07-31 19:25:30 +00:00
|
|
|
)
|
2017-12-31 23:04:49 +00:00
|
|
|
|
2017-01-16 10:06:23 +00:00
|
|
|
def close(self):
|
|
|
|
"""Mock close."""
|
|
|
|
pass
|
|
|
|
|
2016-10-24 06:48:01 +00:00
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def mock_aiohttp_client():
|
|
|
|
"""Context manager to mock aiohttp client."""
|
|
|
|
mocker = AiohttpClientMocker()
|
|
|
|
|
2018-08-20 14:34:18 +00:00
|
|
|
def create_session(hass, *args):
|
|
|
|
session = mocker.create_session(hass.loop)
|
|
|
|
|
|
|
|
async def close_session(event):
|
|
|
|
"""Close session."""
|
|
|
|
await session.close()
|
|
|
|
|
|
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, close_session)
|
|
|
|
|
|
|
|
return session
|
|
|
|
|
2018-03-04 05:28:04 +00:00
|
|
|
with mock.patch(
|
2019-07-31 19:25:30 +00:00
|
|
|
"homeassistant.helpers.aiohttp_client.async_create_clientsession",
|
|
|
|
side_effect=create_session,
|
|
|
|
):
|
2016-10-24 06:48:01 +00:00
|
|
|
yield mocker
|