1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
|
"""Provide common pytest fixtures."""
import asyncio
from collections import deque
from collections.abc import Generator
from copy import deepcopy
import json
from typing import Any
from unittest.mock import AsyncMock, Mock, patch
from aiohttp import ClientSession, ClientWebSocketResponse
from aiohttp.http_websocket import WSMessage, WSMsgType
import pytest
from zwave_js_server.client import Client
from zwave_js_server.model.controller import Controller
from zwave_js_server.model.driver import Driver
from zwave_js_server.model.node import Node, NodeDataType
from . import load_fixture
from .common import MockCommandProtocol
# pylint: disable=protected-access, unused-argument
TEST_URL = "ws://test.org:3000"
@pytest.fixture(name="controller_state", scope="session")
def controller_state_fixture() -> dict[str, Any]:
"""Load the controller state fixture data."""
return json.loads(load_fixture("controller_state.json"))
@pytest.fixture(name="multisensor_6_state", scope="session")
def multisensor_6_state_fixture():
"""Load the multisensor 6 node state fixture data."""
return json.loads(load_fixture("multisensor_6_state.json"))
@pytest.fixture(name="lock_schlage_be469_state", scope="session")
def lock_schlage_be469_state_fixture():
"""Load the schlage lock node state fixture data."""
return json.loads(load_fixture("lock_schlage_be469_state.json"))
@pytest.fixture(name="timed_lock_state", scope="session")
def timed_lock_state_fixture() -> dict[str, Any]:
"""Load the timed lock node state fixture data."""
return json.loads(load_fixture("timed_lock_state.json"))
@pytest.fixture(name="climate_radio_thermostat_ct100_plus_state", scope="session")
def climate_radio_thermostat_ct100_plus_state_fixture():
"""Load the radio thermostat node state fixture data."""
return json.loads(load_fixture("climate_radio_thermostat_ct100_plus_state.json"))
@pytest.fixture(name="cover_qubino_shutter_state", scope="session")
def cover_qubino_shutter_state_fixture():
"""Load the qubino shutter cover node state fixture data."""
return json.loads(load_fixture("cover_qubino_shutter_state.json"))
@pytest.fixture(name="idl_101_lock_state", scope="session")
def idl_101_lock_state_fixture():
"""Load the bad string meta data node state fixture data."""
return json.loads(load_fixture("idl_101_lock_state.json"))
@pytest.fixture(name="wallmote_central_scene_state", scope="session")
def wallmote_central_scene_state_fixture():
"""Load the wallmote central scene node state fixture data."""
return json.loads(load_fixture("wallmote_central_scene_state.json"))
@pytest.fixture(name="unparseable_json_string_value_state", scope="session")
def unparseable_json_string_value_state_fixture():
"""Load the unparseable string json value node state fixture data."""
return json.loads(load_fixture("unparseable_json_string_value_state.json"))
@pytest.fixture(name="partial_and_full_parameter_state", scope="session")
def partial_and_full_parameter_state_fixture():
"""Load the node that has both partial and full parameters state fixture data."""
return json.loads(load_fixture("partial_and_full_parameter_state.json"))
@pytest.fixture(name="invalid_multilevel_sensor_type_state", scope="session")
def invalid_multilevel_sensor_type_state_fixture():
"""Load the node that has an invalid multilevel sensor type state fixture data."""
return json.loads(load_fixture("invalid_multilevel_sensor_type_state.json"))
@pytest.fixture(name="inovelli_switch_state", scope="session")
def inovelli_switch_state_fixture():
"""Load the bad string meta data node state fixture data."""
return json.loads(load_fixture("inovelli_switch_state.json"))
@pytest.fixture(name="ring_keypad_state", scope="session")
def ring_keypad_state_fixture():
"""Load the ring keypad node state fixture data."""
return json.loads(load_fixture("ring_keypad_state.json"))
@pytest.fixture(name="shelly_wave_shutter_state", scope="session")
def shelly_wave_shutter_state_fixture() -> NodeDataType:
"""Load the shelly wave shutter node state fixture data."""
return json.loads(load_fixture("shelly_eu_wave_shutter_state.json"))
@pytest.fixture(name="shelly_wave_shutter")
def shelly_wave_shutter_fixture(
driver: Driver, shelly_wave_shutter_state: NodeDataType
) -> Node:
"""Mock a shelly wave shutter node."""
node = Node(driver.client, deepcopy(shelly_wave_shutter_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="endpoints_with_command_classes_state", scope="session")
def endpoints_with_command_classes_state_fixture():
"""Load the node state fixture data with command classes on the endpoint."""
return json.loads(load_fixture("endpoints_with_command_classes_state.json"))
@pytest.fixture(name="switch_enbrighten_zw3010_state", scope="session")
def switch_enbrighten_zw3010_state_fixture():
"""Load the enbrighten zw3010 switch node state fixture data."""
return json.loads(load_fixture("switch_enbrighten_zw3010_state.json"))
@pytest.fixture(name="energy_production_state", scope="session")
def energy_production_state_fixture():
"""Load a mock node with energy production CC state fixture data."""
return json.loads(load_fixture("energy_production_state.json"))
@pytest.fixture(name="lock_ultraloq_ubolt_pro_state", scope="session")
def lock_ultraloq_ubolt_pro_state_fixture():
"""Load the ultraloq U-Bolt Pro lock state fixture data."""
return json.loads(load_fixture("lock_ultraloq_ubolt_pro_state.json"))
@pytest.fixture(name="device_config", scope="session")
def device_config_fixture() -> dict[str, Any]:
"""Load the device config fixture data."""
return json.loads(load_fixture("device_config.json"))
@pytest.fixture(name="client_session")
def client_session_fixture(ws_client: AsyncMock) -> AsyncMock:
"""Mock an aiohttp client session."""
client_session = AsyncMock(spec_set=ClientSession)
client_session.ws_connect.side_effect = AsyncMock(return_value=ws_client)
return client_session
def create_ws_message(result: dict[str, Any]) -> Mock:
"""Return a mock WSMessage."""
message = Mock(spec_set=WSMessage)
message.type = WSMsgType.TEXT
message.data = json.dumps(result)
message.json.return_value = result
return message
@pytest.fixture(name="messages")
def messages_fixture() -> deque[Mock]:
"""Return a message buffer for the WS client."""
return deque()
@pytest.fixture(name="ws_client")
async def ws_client_fixture(
version_data: dict[str, Any],
ws_message: Mock,
result: dict[str, Any],
messages: deque[Mock],
initialize_data: dict[str, Any],
get_log_config_data: dict[str, Any],
) -> AsyncMock:
"""Mock a websocket client.
This fixture only allows a single message to be received.
"""
ws_client = AsyncMock(spec_set=ClientWebSocketResponse, closed=False)
ws_client.receive_json.side_effect = (
version_data,
initialize_data,
get_log_config_data,
result,
)
for data in (version_data, initialize_data, get_log_config_data, result):
messages.append(create_ws_message(data))
async def receive() -> Mock:
"""Return a websocket message."""
await asyncio.sleep(0)
try:
message = messages.popleft()
except IndexError:
ws_client.closed = True
return WSMessage(WSMsgType.CLOSED, None, None)
return message
ws_client.receive.side_effect = receive
async def close_client(msg: dict[str, Any]) -> None:
"""Close the client."""
if msg["command"] in ("initialize", "start_listening"):
return
# We only want to skip for the initial call
if (
msg["command"] == "driver.get_log_config"
and msg["messageId"] == "get-initial-log-config"
):
return
await asyncio.sleep(0)
ws_client.closed = True
ws_client.send_json.side_effect = close_client
async def reset_close() -> None:
"""Reset the websocket client close method."""
ws_client.closed = True
ws_client.close.side_effect = reset_close
return ws_client
@pytest.fixture(name="await_other")
async def await_other_fixture():
"""Await all other task but the current task."""
async def wait_for_tasks(current_task):
"""Wait for the tasks."""
tasks = asyncio.all_tasks() - {current_task}
await asyncio.gather(*tasks)
return wait_for_tasks
@pytest.fixture(name="driver_ready")
async def driver_ready_fixture():
"""Return an asyncio.Event for driver ready."""
return asyncio.Event()
@pytest.fixture(name="version_data")
def version_data_fixture() -> dict[str, Any]:
"""Return mock version data."""
return {
"type": "version",
"driverVersion": "test_driver_version",
"serverVersion": "test_server_version",
"homeId": "test_home_id",
"minSchemaVersion": 0,
"maxSchemaVersion": 44,
}
@pytest.fixture(name="initialize_data")
def initialize_data_fixture() -> dict[str, Any]:
"""Return mock initialize data."""
return {
"type": "result",
"success": True,
"result": {},
"messageId": "initialize",
}
@pytest.fixture(name="log_config")
def log_config_fixture() -> dict[str, Any]:
"""Return log config."""
return {
"enabled": True,
"level": "info",
"logToFile": False,
"filename": "",
"forceConsole": False,
}
@pytest.fixture(name="get_log_config_data")
def get_log_config_data_fixture(log_config: dict[str, Any]) -> dict[str, Any]:
"""Return mock get_log_config data."""
return {
"type": "result",
"success": True,
"result": {"config": log_config},
"messageId": "get-initial-log-config",
}
@pytest.fixture(name="url")
def url_fixture():
"""Return a test url."""
return TEST_URL
@pytest.fixture(name="result")
def result_fixture(controller_state: dict[str, Any], uuid4: str) -> dict[str, Any]:
"""Return a server result message."""
return {
"type": "result",
"success": True,
"result": {"state": controller_state},
"messageId": uuid4,
}
@pytest.fixture(name="ws_message")
def ws_message_fixture(result: dict[str, Any]) -> Mock:
"""Return a mock WSMessage."""
return create_ws_message(result)
@pytest.fixture(name="uuid4")
def mock_uuid_fixture() -> Generator[str, None, None]:
"""Patch uuid4."""
uuid4_hex = "1234"
with patch("uuid.uuid4") as uuid4:
uuid4.return_value.hex = uuid4_hex
yield uuid4_hex
@pytest.fixture(name="client")
async def client_fixture(
client_session: AsyncMock,
ws_client: AsyncMock,
uuid4: str,
) -> Client:
"""Return a client with a mock websocket transport.
This fixture needs to be a coroutine function to get an event loop
when creating the client.
"""
client = Client("ws://test.org", client_session)
client._client = ws_client
return client
@pytest.fixture(name="mock_command")
def mock_command_fixture(
ws_client: AsyncMock, client: Client, uuid4: str
) -> MockCommandProtocol:
"""Mock a command and response."""
mock_responses: list[tuple[dict, dict, bool]] = []
ack_commands: list[dict] = []
def apply_mock_command(
match_command: dict, response: dict, success: bool = True
) -> list[dict]:
"""Apply the mock command and response return value to the transport.
Return the list with correctly acknowledged commands.
"""
mock_responses.append((match_command, response, success))
return ack_commands
async def set_response(message: dict[str, Any]) -> None:
"""Check the message and set the mocked response if a command matches."""
for match_command, response, success in mock_responses:
if all(message[key] == value for key, value in match_command.items()):
ack_commands.append(message)
received_message = {
"type": "result",
"messageId": uuid4,
"success": success,
}
if success:
received_message["result"] = response
else:
received_message.update(response)
client._handle_incoming_message(received_message)
return
raise RuntimeError("Command not mocked!")
ws_client.send_json.side_effect = set_response
return apply_mock_command
@pytest.fixture(name="driver")
def driver_fixture(
client: Client,
controller_state: dict[str, Any],
log_config: dict[str, Any],
) -> Driver:
"""Return a driver instance with a supporting client."""
client.driver = Driver(client, deepcopy(controller_state), log_config)
return client.driver
@pytest.fixture(name="multisensor_6")
def multisensor_6_fixture(driver, multisensor_6_state):
"""Mock a multisensor 6 node."""
node = Node(driver.client, deepcopy(multisensor_6_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="lock_schlage_be469")
def lock_schlage_be469_fixture(driver, lock_schlage_be469_state):
"""Mock a schlage lock node."""
node = Node(driver.client, deepcopy(lock_schlage_be469_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="timed_lock")
def timed_lock_fixture(driver: Driver, timed_lock_state: dict[str, Any]) -> Node:
"""Mock a schlage lock node."""
node = Node(driver.client, deepcopy(timed_lock_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="climate_radio_thermostat_ct100_plus")
def climate_radio_thermostat_ct100_plus_fixture(
driver, climate_radio_thermostat_ct100_plus_state
):
"""Mock a radio thermostat node."""
node = Node(driver.client, deepcopy(climate_radio_thermostat_ct100_plus_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="cover_qubino_shutter")
def cover_qubino_shutter_fixture(driver, cover_qubino_shutter_state):
"""Mock a qubino shutter cover node."""
node = Node(driver.client, deepcopy(cover_qubino_shutter_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="wallmote_central_scene")
def wallmote_central_scene_fixture(driver, wallmote_central_scene_state):
"""Mock a wallmote central scene node."""
node = Node(driver.client, deepcopy(wallmote_central_scene_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="controller")
def controller_fixture(driver, controller_state):
"""Return a controller instance with a supporting client."""
controller = Controller(driver.client, deepcopy(controller_state))
return controller
@pytest.fixture(name="inovelli_switch")
def inovelli_switch_fixture(driver, inovelli_switch_state):
"""Mock a inovelli switch node."""
node = Node(driver.client, deepcopy(inovelli_switch_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="ring_keypad")
def ring_keypad_fixture(driver, ring_keypad_state):
"""Mock a ring keypad node."""
node = Node(driver.client, deepcopy(ring_keypad_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="partial_and_full_parameter")
def partial_and_full_parameter_fixture(driver, partial_and_full_parameter_state):
"""Mock a node that has both partial and full parameters."""
node = Node(driver.client, deepcopy(partial_and_full_parameter_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="invalid_multilevel_sensor_type")
def invalid_multilevel_sensor_type_fixture(
driver, invalid_multilevel_sensor_type_state
):
"""Mock a node that has invalid multilevel sensor type."""
node = Node(driver.client, deepcopy(invalid_multilevel_sensor_type_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="endpoints_with_command_classes")
def endpoints_with_command_classes_fixture(
driver, endpoints_with_command_classes_state
):
"""Mock a node with command classes on an endpoint."""
node = Node(driver.client, deepcopy(endpoints_with_command_classes_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="switch_enbrighten_zw3010")
def switch_enbrighten_zw3010_fixture(driver, switch_enbrighten_zw3010_state):
"""Mock an Enbrighten ZW3010 switch node."""
node = Node(driver.client, deepcopy(switch_enbrighten_zw3010_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="energy_production")
def energy_prodution_fixture(driver, energy_production_state):
"""Mock a mock node with Energy Production CC."""
node = Node(driver.client, deepcopy(energy_production_state))
driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="lock_ultraloq_ubolt_pro")
def lock_ultraloq_ubolt_pro_fixture(driver, lock_ultraloq_ubolt_pro_state):
"""Mock an Ultraloq U-Bolt Pro lock node."""
node = Node(driver.client, deepcopy(lock_ultraloq_ubolt_pro_state))
driver.controller.nodes[node.node_id] = node
return node
|