| 1 |
"""PyTest fixtures and test helpers.""" |
| 2 |
|
| 3 |
import copy |
| 4 |
import json as _json |
| 5 |
import re |
| 6 |
from datetime import date, timedelta |
| 7 |
|
| 8 |
import logging |
| 9 |
|
| 10 |
from unittest.mock import AsyncMock |
| 11 |
from deepmerge import Merger |
| 12 |
|
| 13 |
from unittest import mock |
| 14 |
|
| 15 |
from aiohttp import ClientResponseError, ClientSession |
| 16 |
|
| 17 |
import pytest |
| 18 |
|
| 19 |
from blebox_uniapi.box_types import get_latest_conf |
| 20 |
from blebox_uniapi.session import ApiHost |
| 21 |
from blebox_uniapi.box import Box |
| 22 |
from blebox_uniapi.error import UnsupportedBoxVersion |
| 23 |
|
| 24 |
_LOGGER = logging.getLogger(__name__) |
| 25 |
|
| 26 |
retype = type(re.compile("")) |
| 27 |
|
| 28 |
|
| 29 |
@pytest.fixture |
| 30 |
def aioclient_mock(): |
| 31 |
return AsyncMock(spec=ClientSession) |
| 32 |
|
| 33 |
|
| 34 |
def array_merge(config, path, base, nxt): |
| 35 |
"""Replace an array element with the merge result of elements.""" |
| 36 |
if len(nxt): |
| 37 |
if isinstance(nxt[0], dict): |
| 38 |
index = 0 |
| 39 |
for item in nxt: |
| 40 |
if not isinstance(item, dict): |
| 41 |
raise NotImplementedError |
| 42 |
my_merger.merge(base[index], item) |
| 43 |
index += 1 |
| 44 |
return base |
| 45 |
elif isinstance(nxt[0], int): |
| 46 |
return [nxt[0]] |
| 47 |
else: |
| 48 |
raise NotImplementedError |
| 49 |
|
| 50 |
|
| 51 |
my_merger = Merger( |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
[(list, [array_merge]), (dict, ["merge"])], |
| 56 |
|
| 57 |
|
| 58 |
["override"], |
| 59 |
|
| 60 |
|
| 61 |
["override"], |
| 62 |
) |
| 63 |
|
| 64 |
|
| 65 |
def jmerge(base, ext): |
| 66 |
"""Create new fixtures by adjusting existing ones.""" |
| 67 |
|
| 68 |
result = copy.deepcopy(base) |
| 69 |
my_merger.merge(result, _json.loads(ext)) |
| 70 |
return result |
| 71 |
|
| 72 |
|
| 73 |
def future_date(delta_days=300): |
| 74 |
"""Generate future date string in 'YYYYMMDD' format.""" |
| 75 |
future_date = date.today() + timedelta(days=delta_days) |
| 76 |
return future_date.strftime("%Y%m%d") |
| 77 |
|
| 78 |
|
| 79 |
HTTP_MOCKS = {} |
| 80 |
|
| 81 |
|
| 82 |
def json_get_expect(mock, url, **kwargs): |
| 83 |
json = kwargs["json"] |
| 84 |
|
| 85 |
if mock not in HTTP_MOCKS: |
| 86 |
HTTP_MOCKS[mock] = {} |
| 87 |
HTTP_MOCKS[mock][url] = json |
| 88 |
|
| 89 |
class EffectWhenGet: |
| 90 |
def __init__(self, key): |
| 91 |
self._key = key |
| 92 |
|
| 93 |
def __call__(self, url, **kwargs): |
| 94 |
data = HTTP_MOCKS[self._key][url] |
| 95 |
response = _json.dumps(data).encode("utf-8") |
| 96 |
status = 200 |
| 97 |
return AiohttpClientMockResponse( |
| 98 |
"GET", |
| 99 |
url, |
| 100 |
status, |
| 101 |
response, |
| 102 |
headers={"content-type": "application/json"}, |
| 103 |
) |
| 104 |
|
| 105 |
mock.get = AsyncMock(side_effect=EffectWhenGet(mock)) |
| 106 |
|
| 107 |
|
| 108 |
def json_post_expect(mock, url, **kwargs): |
| 109 |
json = kwargs["json"] |
| 110 |
params = kwargs["params"] |
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
if mock not in HTTP_MOCKS: |
| 115 |
HTTP_MOCKS[mock] = {} |
| 116 |
if url not in HTTP_MOCKS[mock]: |
| 117 |
HTTP_MOCKS[mock][url] = {} |
| 118 |
|
| 119 |
HTTP_MOCKS[mock][url][params] = json |
| 120 |
|
| 121 |
class EffectWhenPost: |
| 122 |
def __init__(self, key): |
| 123 |
self._key = key |
| 124 |
|
| 125 |
def __call__(self, url, **kwargs): |
| 126 |
|
| 127 |
params = kwargs.get("data") |
| 128 |
|
| 129 |
data = HTTP_MOCKS[self._key][url][params] |
| 130 |
response = _json.dumps(data).encode("utf-8") |
| 131 |
status = 200 |
| 132 |
return AiohttpClientMockResponse( |
| 133 |
"POST", |
| 134 |
url, |
| 135 |
status, |
| 136 |
response, |
| 137 |
headers={"content-type": "application/json"}, |
| 138 |
) |
| 139 |
|
| 140 |
mock.post = AsyncMock(side_effect=EffectWhenPost(mock)) |
| 141 |
|
| 142 |
|
| 143 |
class DefaultBoxTest: |
| 144 |
"""Base class with methods common to BleBox integration tests.""" |
| 145 |
|
| 146 |
IP = "172.0.0.1" |
| 147 |
LOGGER = _LOGGER |
| 148 |
|
| 149 |
async def async_entities(self, session): |
| 150 |
"""Get a created entity at the given index.""" |
| 151 |
|
| 152 |
host = self.IP |
| 153 |
port = 80 |
| 154 |
timeout = 2 |
| 155 |
api_host = ApiHost(host, port, timeout, session, None, self.LOGGER) |
| 156 |
product = await Box.async_from_host(api_host) |
| 157 |
return [ |
| 158 |
self.ENTITY_CLASS(feature) for feature in product.features[self.DEVCLASS] |
| 159 |
] |
| 160 |
|
| 161 |
async def allow_get_info(self, aioclient_mock, info=None): |
| 162 |
"""Stub a HTTP GET request for the device state.""" |
| 163 |
|
| 164 |
data = self.DEVICE_INFO if info is None else info |
| 165 |
|
| 166 |
json_get_expect( |
| 167 |
aioclient_mock, f"http://{self.IP}:80/api/device/state", json=data |
| 168 |
) |
| 169 |
if (hasattr(self, "DEVICE_EXTENDED_INFO")) and ( |
| 170 |
path := getattr(self, "DEVICE_EXTENDED_INFO_PATH") |
| 171 |
): |
| 172 |
data = self.DEVICE_EXTENDED_INFO or info |
| 173 |
json_get_expect( |
| 174 |
aioclient_mock, |
| 175 |
f"http://{self.IP}:80/{path.lstrip('/')}", |
| 176 |
json=data, |
| 177 |
) |
| 178 |
|
| 179 |
def allow_get_state(self, aioclient_mock, data): |
| 180 |
"""Stub a HTTP GET request for the product-specific state.""" |
| 181 |
json_get_expect( |
| 182 |
aioclient_mock, f"http://{self.IP}:80/{self.DEV_INFO_PATH}", json=data |
| 183 |
) |
| 184 |
|
| 185 |
def allow_get(self, aioclient_mock, api_path, data): |
| 186 |
"""Stub a HTTP GET request.""" |
| 187 |
json_get_expect( |
| 188 |
aioclient_mock, f"http://{self.IP}:80/{api_path[1:]}", json=data |
| 189 |
) |
| 190 |
|
| 191 |
async def allow_post(self, code, aioclient_mock, api_path, post_data, response): |
| 192 |
"""Stub a HTTP POST request.""" |
| 193 |
json_post_expect( |
| 194 |
aioclient_mock, |
| 195 |
f"http://{self.IP}:80/{api_path[1:]}", |
| 196 |
params=post_data, |
| 197 |
headers={"content-type": "application/json"}, |
| 198 |
json=response, |
| 199 |
) |
| 200 |
await code() |
| 201 |
|
| 202 |
|
| 203 |
async def updated(self, aioclient_mock, state, index=0): |
| 204 |
"""Return an entry on which update has already been called.""" |
| 205 |
|
| 206 |
await self.allow_get_info(aioclient_mock) |
| 207 |
entity = (await self.async_entities(aioclient_mock))[index] |
| 208 |
|
| 209 |
self.allow_get_state(aioclient_mock, state) |
| 210 |
await entity.async_update() |
| 211 |
return entity |
| 212 |
|
| 213 |
async def test_future_version(self, aioclient_mock): |
| 214 |
""" |
| 215 |
Test support for future versions, that is last supported entry in config type file. |
| 216 |
""" |
| 217 |
await self.allow_get_info(aioclient_mock, self.DEVICE_INFO_FUTURE) |
| 218 |
entity = (await self.async_entities(aioclient_mock))[0] |
| 219 |
|
| 220 |
assert entity._feature.product._config is get_latest_conf( |
| 221 |
entity._feature.product.type |
| 222 |
) |
| 223 |
|
| 224 |
async def test_latest_version(self, aioclient_mock): |
| 225 |
""" |
| 226 |
Test support for latest versions, that is last supported entry in config type file. |
| 227 |
""" |
| 228 |
await self.allow_get_info(aioclient_mock, self.DEVICE_INFO_LATEST) |
| 229 |
entity = (await self.async_entities(aioclient_mock))[0] |
| 230 |
|
| 231 |
assert entity._feature.product._config is get_latest_conf( |
| 232 |
entity._feature.product.type |
| 233 |
) |
| 234 |
|
| 235 |
async def test_unsupported_version(self, aioclient_mock): |
| 236 |
"""Test version support.""" |
| 237 |
|
| 238 |
|
| 239 |
if self.DEVICE_INFO != self.DEVICE_INFO_UNSUPPORTED: |
| 240 |
await self.allow_get_info(aioclient_mock, self.DEVICE_INFO_UNSUPPORTED) |
| 241 |
with pytest.raises(UnsupportedBoxVersion): |
| 242 |
await self.async_entities(aioclient_mock) |
| 243 |
|
| 244 |
async def test_unspecified_version(self, aioclient_mock): |
| 245 |
""" |
| 246 |
Test default_api_level when api level is not specified in device info. |
| 247 |
|
| 248 |
""" |
| 249 |
if self.DEVICE_INFO_UNSPECIFIED_API is not None: |
| 250 |
await self.allow_get_info(aioclient_mock, self.DEVICE_INFO_UNSPECIFIED_API) |
| 251 |
with pytest.raises(UnsupportedBoxVersion): |
| 252 |
await self.async_entities(aioclient_mock) |
| 253 |
|
| 254 |
|
| 255 |
class AiohttpClientMockResponse: |
| 256 |
"""Mock Aiohttp client response.""" |
| 257 |
|
| 258 |
def __init__( |
| 259 |
self, method, url, status, response, cookies=None, exc=None, headers=None |
| 260 |
): |
| 261 |
"""Initialize a fake response.""" |
| 262 |
self.method = method |
| 263 |
self._url = url |
| 264 |
self.status = status |
| 265 |
self.response = response |
| 266 |
self.exc = exc |
| 267 |
|
| 268 |
self._headers = headers or {} |
| 269 |
self._cookies = {} |
| 270 |
|
| 271 |
if cookies: |
| 272 |
for name, data in cookies.items(): |
| 273 |
cookie = mock.MagicMock() |
| 274 |
cookie.value = data |
| 275 |
self._cookies[name] = cookie |
| 276 |
|
| 277 |
@property |
| 278 |
def headers(self): |
| 279 |
return self._headers |
| 280 |
|
| 281 |
@property |
| 282 |
def cookies(self): |
| 283 |
return self._cookies |
| 284 |
|
| 285 |
@property |
| 286 |
def url(self): |
| 287 |
return self._url |
| 288 |
|
| 289 |
@property |
| 290 |
def content_type(self): |
| 291 |
return self._headers.get("content-type") |
| 292 |
|
| 293 |
async def read(self): |
| 294 |
return self.response |
| 295 |
|
| 296 |
async def text(self, encoding="utf-8"): |
| 297 |
return self.response.decode(encoding) |
| 298 |
|
| 299 |
async def json(self, encoding="utf-8"): |
| 300 |
return _json.loads(self.response.decode(encoding)) |
| 301 |
|
| 302 |
async def release(self): |
| 303 |
pass |
| 304 |
|
| 305 |
def raise_for_status(self): |
| 306 |
"""Raise error if status is 400 or higher.""" |
| 307 |
if self.status >= 400: |
| 308 |
request_info = mock.Mock(real_url="http://example.com") |
| 309 |
|
| 310 |
raise ClientResponseError( |
| 311 |
request_info=request_info, |
| 312 |
history=None, |
| 313 |
code=self.status, |
| 314 |
headers=self.headers, |
| 315 |
) |
| 316 |
|
| 317 |
def close(self): |
| 318 |
pass |
| 319 |
|
| 320 |
|
| 321 |
class CommonEntity: |
| 322 |
def __init__(self, feature): |
| 323 |
self._feature = feature |
| 324 |
|
| 325 |
@property |
| 326 |
def name(self): |
| 327 |
return self._feature.full_name |
| 328 |
|
| 329 |
@property |
| 330 |
def unique_id(self): |
| 331 |
return self._feature.unique_id |
| 332 |
|
| 333 |
async def async_update(self): |
| 334 |
await self._feature.async_update() |
| 335 |
|
| 336 |
@property |
| 337 |
def device_info(self): |
| 338 |
product = self._feature.product |
| 339 |
return { |
| 340 |
"name": product.name, |
| 341 |
"mac": product.unique_id, |
| 342 |
"manufacturer": product.brand, |
| 343 |
"model": product.model, |
| 344 |
"sw_version": product.firmware_version, |
| 345 |
} |