response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Remove side_effect to pymodbus calls. | def do_exception_fixture():
"""Remove side_effect to pymodbus calls."""
return False |
Mock pymodbus. | def mock_pymodbus_fixture(do_exception, register_words):
"""Mock pymodbus."""
mock_pb = mock.AsyncMock()
mock_pb.close = mock.MagicMock()
read_result = ReadResult(register_words if register_words else [])
mock_pb.read_coils.return_value = read_result
mock_pb.read_discrete_inputs.return_value = read_result
mock_pb.read_input_registers.return_value = read_result
mock_pb.read_holding_registers.return_value = read_result
mock_pb.write_register.return_value = read_result
mock_pb.write_registers.return_value = read_result
mock_pb.write_coil.return_value = read_result
mock_pb.write_coils.return_value = read_result
if do_exception:
exc = ModbusException("mocked pymodbus exception")
mock_pb.read_coils.side_effect = exc
mock_pb.read_discrete_inputs.side_effect = exc
mock_pb.read_input_registers.side_effect = exc
mock_pb.read_holding_registers.side_effect = exc
mock_pb.write_register.side_effect = exc
mock_pb.write_registers.side_effect = exc
mock_pb.write_coil.side_effect = exc
mock_pb.write_coils.side_effect = exc
with (
mock.patch(
"homeassistant.components.modbus.modbus.AsyncModbusTcpClient",
return_value=mock_pb,
autospec=True,
),
mock.patch(
"homeassistant.components.modbus.modbus.AsyncModbusSerialClient",
return_value=mock_pb,
autospec=True,
),
mock.patch(
"homeassistant.components.modbus.modbus.AsyncModbusUdpClient",
return_value=mock_pb,
autospec=True,
),
):
yield mock_pb |
Mock modem. | def patch_init_modem():
"""Mock modem."""
return patch(
"homeassistant.components.modem_callerid.PhoneModem.initialize",
) |
Mock modem config flow. | def patch_config_flow_modem():
"""Mock modem config flow."""
return patch(
"homeassistant.components.modem_callerid.config_flow.PhoneModem.test",
) |
Mock of a serial port. | def com_port():
"""Mock of a serial port."""
port = ListPortInfo(DEFAULT_PORT)
port.serial_number = "1234"
port.manufacturer = "Virtual serial port"
port.device = DEFAULT_PORT
port.description = "Some serial port"
return port |
Set up things to be run when tests are started. | def init_sensors_fixture(hass):
"""Set up things to be run when tests are started."""
hass.states.async_set(
"test.indoortemp", "20", {ATTR_UNIT_OF_MEASUREMENT: UnitOfTemperature.CELSIUS}
)
hass.states.async_set(
"test.outdoortemp", "10", {ATTR_UNIT_OF_MEASUREMENT: UnitOfTemperature.CELSIUS}
)
hass.states.async_set(
"test.indoorhumidity", "50", {ATTR_UNIT_OF_MEASUREMENT: PERCENTAGE}
) |
Return the default mocked config entry. | def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="Moon",
domain=DOMAIN,
) |
Mock setting up a config entry. | def mock_setup_entry() -> Generator[None, None, None]:
"""Mock setting up a config entry."""
with patch("homeassistant.components.moon.async_setup_entry", return_value=True):
yield |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Mock motion blinds ble connection and entry setup. | def motion_blinds_connect_fixture(enable_bluetooth):
"""Mock motion blinds ble connection and entry setup."""
device = Mock()
device.name = TEST_NAME
device.address = TEST_ADDRESS
bleak_scanner = AsyncMock()
bleak_scanner.discover.return_value = [device]
with (
patch(
"homeassistant.components.motionblinds_ble.config_flow.bluetooth.async_scanner_count",
return_value=1,
),
patch(
"homeassistant.components.motionblinds_ble.config_flow.bluetooth.async_get_scanner",
return_value=bleak_scanner,
),
patch(
"homeassistant.components.motionblinds_ble.async_setup_entry",
return_value=True,
),
):
yield bleak_scanner, device |
Return aiohttp_server and allow opening sockets. | def aiohttp_server(event_loop, aiohttp_server, socket_enabled):
"""Return aiohttp_server and allow opening sockets."""
return aiohttp_server |
Create mock motionEye client. | def create_mock_motioneye_client() -> AsyncMock:
"""Create mock motionEye client."""
mock_client = AsyncMock()
mock_client.async_client_login = AsyncMock(return_value={})
mock_client.async_get_cameras = AsyncMock(return_value=TEST_CAMERAS)
mock_client.async_client_close = AsyncMock(return_value=True)
mock_client.get_camera_snapshot_url = Mock(return_value="")
mock_client.get_camera_stream_url = Mock(return_value="")
return mock_client |
Add a test config entry. | def create_mock_motioneye_config_entry(
hass: HomeAssistant,
data: dict[str, Any] | None = None,
options: dict[str, Any] | None = None,
) -> ConfigEntry:
"""Add a test config entry."""
config_entry: MockConfigEntry = MockConfigEntry(
entry_id=TEST_CONFIG_ENTRY_ID,
domain=DOMAIN,
data=data or {CONF_URL: TEST_URL},
title=f"{TEST_URL}",
options=options or {},
)
config_entry.add_to_hass(hass)
return config_entry |
Register a test entity. | def register_test_entity(
hass: HomeAssistant, platform: str, camera_id: int, type_name: str, entity_id: str
) -> None:
"""Register a test entity."""
unique_id = get_motioneye_entity_unique_id(
TEST_CONFIG_ENTRY_ID, camera_id, type_name
)
entity_id = entity_id.split(".")[1]
entity_registry = er.async_get(hass)
entity_registry.async_get_or_create(
platform,
DOMAIN,
unique_id,
suggested_object_id=entity_id,
disabled_by=None,
) |
Return the default mocked config entry. | def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title=ZEROCONF_NAME,
domain=DOMAIN,
data={CONF_HOST: HOST, CONF_PORT: PORT},
unique_id=ZEROCONF_MAC,
) |
Mock setting up a config entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Mock setting up a config entry."""
with patch(
"homeassistant.components.motionmount.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry |
Return a mocked MotionMount config flow. | def mock_motionmount_config_flow() -> Generator[None, MagicMock, None]:
"""Return a mocked MotionMount config flow."""
with patch(
"homeassistant.components.motionmount.config_flow.motionmount.MotionMount",
autospec=True,
) as motionmount_mock:
client = motionmount_mock.return_value
yield client |
Mock Motionblinds connection and entry setup. | def motion_blinds_connect_fixture(mock_get_source_ip):
"""Mock Motionblinds connection and entry setup."""
with (
patch(
"homeassistant.components.motion_blinds.gateway.MotionGateway.GetDeviceList",
return_value=True,
),
patch(
"homeassistant.components.motion_blinds.gateway.MotionGateway.Update",
return_value=True,
),
patch(
"homeassistant.components.motion_blinds.gateway.MotionGateway.Check_gateway_multicast",
return_value=True,
),
patch(
"homeassistant.components.motion_blinds.gateway.MotionGateway.device_list",
TEST_DEVICE_LIST,
),
patch(
"homeassistant.components.motion_blinds.gateway.MotionGateway.mac",
TEST_MAC,
),
patch(
"homeassistant.components.motion_blinds.config_flow.MotionDiscovery.discover",
return_value=TEST_DISCOVERY_1,
),
patch(
"homeassistant.components.motion_blinds.config_flow.MotionGateway.GetDeviceList",
return_value=True,
),
patch(
"homeassistant.components.motion_blinds.config_flow.MotionGateway.available",
True,
),
patch(
"homeassistant.components.motion_blinds.gateway.AsyncMotionMulticast.Start_listen",
return_value=True,
),
patch(
"homeassistant.components.motion_blinds.gateway.AsyncMotionMulticast.Stop_listen",
return_value=True,
),
patch(
"homeassistant.components.motion_blinds.gateway.network.async_get_adapters",
return_value=TEST_INTERFACES,
),
patch(
"homeassistant.components.motion_blinds.async_setup_entry",
return_value=True,
),
):
yield |
Patch configuration.yaml. | def patch_hass_config(mock_hass_config: None) -> None:
"""Patch configuration.yaml.""" |
Set an alternate temp dir prefix. | def temp_dir_prefix() -> str:
"""Set an alternate temp dir prefix."""
return "test" |
Mock the certificate temp directory. | def mock_temp_dir(temp_dir_prefix: str) -> Generator[None, None, str]:
"""Mock the certificate temp directory."""
with patch(
# Patch temp dir name to avoid tests fail running in parallel
"homeassistant.components.mqtt.util.TEMP_DIR_NAME",
f"home-assistant-mqtt-{temp_dir_prefix}-{getrandbits(10):03x}",
) as mocked_temp_dir:
yield mocked_temp_dir |
Test of a call. | def help_all_subscribe_calls(mqtt_client_mock: MqttMockPahoClient) -> list[Any]:
"""Test of a call."""
all_calls = []
for calls in mqtt_client_mock.subscribe.mock_calls:
for call in calls[1]:
all_calls.extend(call)
return all_calls |
Tweak a default config for parametrization.
Returns a custom config to be used as parametrization for with hass_config,
based on the supplied mqtt_base_config and updated with mqtt_entity_configs.
For each item in mqtt_entity_configs an entity instance is added to the config. | def help_custom_config(
mqtt_entity_domain: str,
mqtt_base_config: ConfigType,
mqtt_entity_configs: Iterable[ConfigType],
) -> ConfigType:
"""Tweak a default config for parametrization.
Returns a custom config to be used as parametrization for with hass_config,
based on the supplied mqtt_base_config and updated with mqtt_entity_configs.
For each item in mqtt_entity_configs an entity instance is added to the config.
"""
config: ConfigType = copy.deepcopy(mqtt_base_config)
entity_instances: list[ConfigType] = []
for instance in mqtt_entity_configs:
base: ConfigType = copy.deepcopy(
mqtt_base_config[mqtt.DOMAIN][mqtt_entity_domain]
)
base.update(instance)
entity_instances.append(base)
config[mqtt.DOMAIN][mqtt_entity_domain]: list[ConfigType] = entity_instances
return config |
Mock out the finish setup method. | def mock_finish_setup() -> Generator[MagicMock, None, None]:
"""Mock out the finish setup method."""
with patch(
"homeassistant.components.mqtt.MQTT.async_connect", return_value=True
) as mock_finish:
yield mock_finish |
Mock the client certificate check. | def mock_client_cert_check_fail() -> Generator[MagicMock, None, None]:
"""Mock the client certificate check."""
with patch(
"homeassistant.components.mqtt.config_flow.load_pem_x509_certificate",
side_effect=ValueError,
) as mock_cert_check:
yield mock_cert_check |
Mock the client key file check. | def mock_client_key_check_fail() -> Generator[MagicMock, None, None]:
"""Mock the client key file check."""
with patch(
"homeassistant.components.mqtt.config_flow.load_pem_private_key",
side_effect=ValueError,
) as mock_key_check:
yield mock_key_check |
Mock the SSL context used to load the cert chain and to load verify locations. | def mock_ssl_context() -> Generator[dict[str, MagicMock], None, None]:
"""Mock the SSL context used to load the cert chain and to load verify locations."""
with (
patch("homeassistant.components.mqtt.config_flow.SSLContext") as mock_context,
patch(
"homeassistant.components.mqtt.config_flow.load_pem_private_key"
) as mock_key_check,
patch(
"homeassistant.components.mqtt.config_flow.load_pem_x509_certificate"
) as mock_cert_check,
):
yield {
"context": mock_context,
"load_pem_x509_certificate": mock_cert_check,
"load_pem_private_key": mock_key_check,
} |
Mock out the reload after updating the entry. | def mock_reload_after_entry_update() -> Generator[MagicMock, None, None]:
"""Mock out the reload after updating the entry."""
with patch(
"homeassistant.components.mqtt._async_config_entry_updated"
) as mock_reload:
yield mock_reload |
Mock the try connection method. | def mock_try_connection() -> Generator[MagicMock, None, None]:
"""Mock the try connection method."""
with patch("homeassistant.components.mqtt.config_flow.try_connection") as mock_try:
yield mock_try |
Mock the try connection method with success. | def mock_try_connection_success() -> Generator[MqttMockPahoClient, None, None]:
"""Mock the try connection method with success."""
_mid = 1
def get_mid():
nonlocal _mid
_mid += 1
return _mid
def loop_start():
"""Simulate connect on loop start."""
mock_client().on_connect(mock_client, None, None, 0)
def _subscribe(topic, qos=0):
mid = get_mid()
mock_client().on_subscribe(mock_client, 0, mid)
return (0, mid)
def _unsubscribe(topic):
mid = get_mid()
mock_client().on_unsubscribe(mock_client, 0, mid)
return (0, mid)
with patch("paho.mqtt.client.Client") as mock_client:
mock_client().loop_start = loop_start
mock_client().subscribe = _subscribe
mock_client().unsubscribe = _unsubscribe
yield mock_client() |
Mock the try connection method with a time out. | def mock_try_connection_time_out() -> Generator[MagicMock, None, None]:
"""Mock the try connection method with a time out."""
# Patch prevent waiting 5 sec for a timeout
with (
patch("paho.mqtt.client.Client") as mock_client,
patch("homeassistant.components.mqtt.config_flow.MQTT_TIMEOUT", 0),
):
mock_client().loop_start = lambda *args: 1
yield mock_client() |
Mock upload certificate files. | def mock_process_uploaded_file(
tmp_path: Path, mock_temp_dir: str
) -> Generator[MagicMock, None, None]:
"""Mock upload certificate files."""
file_id_ca = str(uuid4())
file_id_cert = str(uuid4())
file_id_key = str(uuid4())
@contextmanager
def _mock_process_uploaded_file(
hass: HomeAssistant, file_id: str
) -> Iterator[Path | None]:
if file_id == file_id_ca:
with open(tmp_path / "ca.crt", "wb") as cafile:
cafile.write(b"## mock CA certificate file ##")
yield tmp_path / "ca.crt"
elif file_id == file_id_cert:
with open(tmp_path / "client.crt", "wb") as certfile:
certfile.write(b"## mock client certificate file ##")
yield tmp_path / "client.crt"
elif file_id == file_id_key:
with open(tmp_path / "client.key", "wb") as keyfile:
keyfile.write(b"## mock key file ##")
yield tmp_path / "client.key"
else:
pytest.fail(f"Unexpected file_id: {file_id}")
with patch(
"homeassistant.components.mqtt.config_flow.process_uploaded_file",
side_effect=_mock_process_uploaded_file,
) as mock_upload:
mock_upload.file_id = {
mqtt.CONF_CERTIFICATE: file_id_ca,
mqtt.CONF_CLIENT_CERT: file_id_cert,
mqtt.CONF_CLIENT_KEY: file_id_key,
}
yield mock_upload |
Get default value for key in voluptuous schema. | def get_default(schema: vol.Schema, key: str) -> Any:
"""Get default value for key in voluptuous schema."""
for schema_key in schema:
if schema_key == key:
if schema_key.default == vol.UNDEFINED:
return None
return schema_key.default() |
Get suggested value for key in voluptuous schema. | def get_suggested(schema: vol.Schema, key: str) -> Any:
"""Get suggested value for key in voluptuous schema."""
for schema_key in schema:
if schema_key == key:
if (
schema_key.description is None
or "suggested_value" not in schema_key.description
):
return None
return schema_key.description["suggested_value"] |
Stub copying the blueprints to the config folder. | def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder.""" |
Track calls to a mock service. | def calls(hass: HomeAssistant) -> list[ServiceCall]:
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") |
Autouse hass_storage for the TestCase tests. | def mock_storage(hass_storage: dict[str, Any]) -> None:
"""Autouse hass_storage for the TestCase tests.""" |
Fixture to hold recorded calls. | def calls() -> list[ReceiveMessage]:
"""Fixture to hold recorded calls."""
return [] |
Fixture to record calls. | def record_calls(calls: list[ReceiveMessage]) -> MessageCallbackType:
"""Fixture to record calls."""
@callback
def record_calls(msg: ReceiveMessage) -> None:
"""Record calls."""
calls.append(msg)
return record_calls |
Return True if all of the given attributes match with the message. | def help_assert_message(
msg: ReceiveMessage,
topic: str | None = None,
payload: str | None = None,
qos: int | None = None,
retain: bool | None = None,
) -> bool:
"""Return True if all of the given attributes match with the message."""
match: bool = True
if topic is not None:
match &= msg.topic == topic
if payload is not None:
match &= msg.payload == payload
if qos is not None:
match &= msg.qos == qos
if retain is not None:
match &= msg.retain == retain
return match |
Test topic name/filter validation. | def test_validate_topic() -> None:
"""Test topic name/filter validation."""
# Invalid UTF-8, must not contain U+D800 to U+DFFF.
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\ud800")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\udfff")
# Topic MUST NOT be empty
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("")
# Topic MUST NOT be longer than 65535 encoded bytes.
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("ü" * 32768)
# UTF-8 MUST NOT include null character
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("bad\0one")
# Topics "SHOULD NOT" include these special characters
# (not MUST NOT, RFC2119). The receiver MAY close the connection.
# We enforce this because mosquitto does: https://github.com/eclipse/mosquitto/commit/94fdc9cb44c829ff79c74e1daa6f7d04283dfffd
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\u0001")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\u001f")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\u007f")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\u009f")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\ufdd0")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\ufdef")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\ufffe")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\ufffe")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\uffff")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\U0001fffe")
with pytest.raises(vol.Invalid):
mqtt.util.valid_topic("\U0001ffff") |
Test invalid subscribe topics. | def test_validate_subscribe_topic() -> None:
"""Test invalid subscribe topics."""
mqtt.valid_subscribe_topic("#")
mqtt.valid_subscribe_topic("sport/#")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("sport/#/")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("foo/bar#")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("foo/#/bar")
mqtt.valid_subscribe_topic("+")
mqtt.valid_subscribe_topic("+/tennis/#")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("sport+")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("sport+/")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("sport/+1")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("sport/+#")
with pytest.raises(vol.Invalid):
mqtt.valid_subscribe_topic("bad+topic")
mqtt.valid_subscribe_topic("sport/+/player1")
mqtt.valid_subscribe_topic("/finance")
mqtt.valid_subscribe_topic("+/+")
mqtt.valid_subscribe_topic("$SYS/#") |
Test invalid publish topics. | def test_validate_publish_topic() -> None:
"""Test invalid publish topics."""
with pytest.raises(vol.Invalid):
mqtt.valid_publish_topic("pub+")
with pytest.raises(vol.Invalid):
mqtt.valid_publish_topic("pub/+")
with pytest.raises(vol.Invalid):
mqtt.valid_publish_topic("1#")
with pytest.raises(vol.Invalid):
mqtt.valid_publish_topic("bad+topic")
mqtt.valid_publish_topic("//")
# Topic names beginning with $ SHOULD NOT be used, but can
mqtt.valid_publish_topic("$SYS/") |
Test MQTT entity device info validation. | def test_entity_device_info_schema() -> None:
"""Test MQTT entity device info validation."""
# just identifier
MQTT_ENTITY_DEVICE_INFO_SCHEMA({"identifiers": ["abcd"]})
MQTT_ENTITY_DEVICE_INFO_SCHEMA({"identifiers": "abcd"})
# just connection
MQTT_ENTITY_DEVICE_INFO_SCHEMA(
{"connections": [[dr.CONNECTION_NETWORK_MAC, "02:5b:26:a8:dc:12"]]}
)
# full device info
MQTT_ENTITY_DEVICE_INFO_SCHEMA(
{
"identifiers": ["helloworld", "hello"],
"connections": [
[dr.CONNECTION_NETWORK_MAC, "02:5b:26:a8:dc:12"],
[dr.CONNECTION_ZIGBEE, "zigbee_id"],
],
"manufacturer": "Whatever",
"name": "Beer",
"model": "Glass",
"serial_number": "1234deadbeef",
"sw_version": "0.1-beta",
"configuration_url": "http://example.com",
}
)
# full device info with via_device
MQTT_ENTITY_DEVICE_INFO_SCHEMA(
{
"identifiers": ["helloworld", "hello"],
"connections": [
[dr.CONNECTION_NETWORK_MAC, "02:5b:26:a8:dc:12"],
[dr.CONNECTION_ZIGBEE, "zigbee_id"],
],
"manufacturer": "Whatever",
"name": "Beer",
"model": "Glass",
"serial_number": "1234deadbeef",
"sw_version": "0.1-beta",
"via_device": "test-hub",
"configuration_url": "http://example.com",
}
)
# no identifiers
with pytest.raises(vol.Invalid):
MQTT_ENTITY_DEVICE_INFO_SCHEMA(
{
"manufacturer": "Whatever",
"name": "Beer",
"model": "Glass",
"sw_version": "0.1-beta",
}
)
# empty identifiers
with pytest.raises(vol.Invalid):
MQTT_ENTITY_DEVICE_INFO_SCHEMA(
{"identifiers": [], "connections": [], "name": "Beer"}
)
# not an valid URL
with pytest.raises(vol.Invalid):
MQTT_ENTITY_DEVICE_INFO_SCHEMA(
{
"manufacturer": "Whatever",
"name": "Beer",
"model": "Glass",
"sw_version": "0.1-beta",
"configuration_url": "fake://link",
}
) |
Fixture to mock tag. | def tag_mock() -> Generator[AsyncMock, None, None]:
"""Fixture to mock tag."""
with patch("homeassistant.components.tag.async_scan_tag") as mock_tag:
yield mock_tag |
Stub copying the blueprints to the config folder. | def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None:
"""Stub copying the blueprints to the config folder.""" |
Track calls to a mock service. | def calls(hass: HomeAssistant):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") |
Mock the MQTT integration. | def mock_mqtt_fixture(hass: HomeAssistant) -> None:
"""Mock the MQTT integration."""
hass.config.components.add(MQTT_DOMAIN) |
Patch the serial port check. | def is_serial_port_fixture() -> Generator[MagicMock, None, None]:
"""Patch the serial port check."""
with patch("homeassistant.components.mysensors.gateway.cv.isdevice") as is_device:
is_device.side_effect = lambda device: device
yield is_device |
Return the gateway nodes dict. | def gateway_nodes_fixture() -> dict[int, Sensor]:
"""Return the gateway nodes dict."""
return {} |
Mock the gateway features. | def mock_gateway_features(
persistence: MagicMock, transport_class: MagicMock, nodes: dict[int, Sensor]
) -> None:
"""Mock the gateway features."""
async def mock_schedule_save_sensors() -> None:
"""Load nodes from via persistence."""
gateway = transport_class.call_args[0][0]
gateway.sensors.update(nodes)
persistence.schedule_save_sensors = AsyncMock(
side_effect=mock_schedule_save_sensors
)
# For some reason autospeccing does not recognize these methods.
persistence.safe_load_sensors = MagicMock()
persistence.save_sensors = MagicMock()
async def mock_connect() -> None:
"""Mock the start method."""
transport.connect_task = MagicMock()
gateway = transport_class.call_args[0][0]
gateway.on_conn_made(gateway)
transport = transport_class.return_value
transport.connect_task = None
transport.connect.side_effect = mock_connect |
Return the default mocked transport. | def transport_fixture(serial_transport: MagicMock) -> MagicMock:
"""Return the default mocked transport."""
return serial_transport |
Return the transport mock that accepts string messages. | def transport_write(transport: MagicMock) -> MagicMock:
"""Return the transport mock that accepts string messages."""
return transport.return_value.send |
Provide the config entry used for integration set up. | def config_entry_fixture(serial_entry: MockConfigEntry) -> MockConfigEntry:
"""Provide the config entry used for integration set up."""
return serial_entry |
Receive a message for the gateway. | def receive_message(
transport: MagicMock, integration: MockConfigEntry
) -> Callable[[str], None]:
"""Receive a message for the gateway."""
def receive_message_callback(message_string: str) -> None:
"""Receive a message with the transport.
The message_string parameter is a string in the MySensors message format.
"""
gateway = transport.call_args[0][0]
# node_id;child_id;command;ack;type;payload\n
gateway.logic(message_string)
return receive_message_callback |
Return a setup gateway. | def gateway_fixture(
transport: MagicMock, integration: MockConfigEntry
) -> BaseSyncGateway:
"""Return a setup gateway."""
return transport.call_args[0][0] |
Load mysensors nodes fixture. | def load_nodes_state(fixture_path: str) -> dict:
"""Load mysensors nodes fixture."""
return json.loads(
load_fixture(fixture_path, integration=DOMAIN), cls=MySensorsJSONDecoder
) |
Update the gateway nodes. | def update_gateway_nodes(
gateway_nodes: dict[int, Sensor], nodes: dict[int, Sensor]
) -> dict:
"""Update the gateway nodes."""
gateway_nodes.update(nodes)
return nodes |
Load the cover node state. | def cover_node_binary_state_fixture() -> dict:
"""Load the cover node state."""
return load_nodes_state("cover_node_binary_state.json") |
Load the cover child node. | def cover_node_binary(
gateway_nodes: dict[int, Sensor], cover_node_binary_state: dict
) -> Sensor:
"""Load the cover child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(cover_node_binary_state))
return nodes[1] |
Load the cover node state. | def cover_node_percentage_state_fixture() -> dict:
"""Load the cover node state."""
return load_nodes_state("cover_node_percentage_state.json") |
Load the cover child node. | def cover_node_percentage(
gateway_nodes: dict[int, Sensor], cover_node_percentage_state: dict
) -> Sensor:
"""Load the cover child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(cover_node_percentage_state))
return nodes[1] |
Load the door sensor state. | def door_sensor_state_fixture() -> dict:
"""Load the door sensor state."""
return load_nodes_state("door_sensor_state.json") |
Load the door sensor. | def door_sensor(gateway_nodes: dict[int, Sensor], door_sensor_state: dict) -> Sensor:
"""Load the door sensor."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(door_sensor_state))
return nodes[1] |
Load the gps sensor state. | def gps_sensor_state_fixture() -> dict:
"""Load the gps sensor state."""
return load_nodes_state("gps_sensor_state.json") |
Load the gps sensor. | def gps_sensor(gateway_nodes: dict[int, Sensor], gps_sensor_state: dict) -> Sensor:
"""Load the gps sensor."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(gps_sensor_state))
return nodes[1] |
Load the dimmer node state. | def dimmer_node_state_fixture() -> dict:
"""Load the dimmer node state."""
return load_nodes_state("dimmer_node_state.json") |
Load the dimmer child node. | def dimmer_node(gateway_nodes: dict[int, Sensor], dimmer_node_state: dict) -> Sensor:
"""Load the dimmer child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(dimmer_node_state))
return nodes[1] |
Load the hvac node auto state. | def hvac_node_auto_state_fixture() -> dict:
"""Load the hvac node auto state."""
return load_nodes_state("hvac_node_auto_state.json") |
Load the hvac auto child node. | def hvac_node_auto(
gateway_nodes: dict[int, Sensor], hvac_node_auto_state: dict
) -> Sensor:
"""Load the hvac auto child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(hvac_node_auto_state))
return nodes[1] |
Load the hvac node cool state. | def hvac_node_cool_state_fixture() -> dict:
"""Load the hvac node cool state."""
return load_nodes_state("hvac_node_cool_state.json") |
Load the hvac cool child node. | def hvac_node_cool(
gateway_nodes: dict[int, Sensor], hvac_node_cool_state: dict
) -> Sensor:
"""Load the hvac cool child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(hvac_node_cool_state))
return nodes[1] |
Load the hvac node heat state. | def hvac_node_heat_state_fixture() -> dict:
"""Load the hvac node heat state."""
return load_nodes_state("hvac_node_heat_state.json") |
Load the hvac heat child node. | def hvac_node_heat(
gateway_nodes: dict[int, Sensor], hvac_node_heat_state: dict
) -> Sensor:
"""Load the hvac heat child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(hvac_node_heat_state))
return nodes[1] |
Load the power sensor state. | def power_sensor_state_fixture() -> dict:
"""Load the power sensor state."""
return load_nodes_state("power_sensor_state.json") |
Load the power sensor. | def power_sensor(gateway_nodes: dict[int, Sensor], power_sensor_state: dict) -> Sensor:
"""Load the power sensor."""
nodes = update_gateway_nodes(gateway_nodes, power_sensor_state)
return nodes[1] |
Load the rgb node state. | def rgb_node_state_fixture() -> dict:
"""Load the rgb node state."""
return load_nodes_state("rgb_node_state.json") |
Load the rgb child node. | def rgb_node(gateway_nodes: dict[int, Sensor], rgb_node_state: dict) -> Sensor:
"""Load the rgb child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(rgb_node_state))
return nodes[1] |
Load the rgbw node state. | def rgbw_node_state_fixture() -> dict:
"""Load the rgbw node state."""
return load_nodes_state("rgbw_node_state.json") |
Load the rgbw child node. | def rgbw_node(gateway_nodes: dict[int, Sensor], rgbw_node_state: dict) -> Sensor:
"""Load the rgbw child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(rgbw_node_state))
return nodes[1] |
Load the energy sensor state. | def energy_sensor_state_fixture() -> dict:
"""Load the energy sensor state."""
return load_nodes_state("energy_sensor_state.json") |
Load the energy sensor. | def energy_sensor(
gateway_nodes: dict[int, Sensor], energy_sensor_state: dict
) -> Sensor:
"""Load the energy sensor."""
nodes = update_gateway_nodes(gateway_nodes, energy_sensor_state)
return nodes[1] |
Load the sound sensor state. | def sound_sensor_state_fixture() -> dict:
"""Load the sound sensor state."""
return load_nodes_state("sound_sensor_state.json") |
Load the sound sensor. | def sound_sensor(gateway_nodes: dict[int, Sensor], sound_sensor_state: dict) -> Sensor:
"""Load the sound sensor."""
nodes = update_gateway_nodes(gateway_nodes, sound_sensor_state)
return nodes[1] |
Load the distance sensor state. | def distance_sensor_state_fixture() -> dict:
"""Load the distance sensor state."""
return load_nodes_state("distance_sensor_state.json") |
Load the distance sensor. | def distance_sensor(
gateway_nodes: dict[int, Sensor], distance_sensor_state: dict
) -> Sensor:
"""Load the distance sensor."""
nodes = update_gateway_nodes(gateway_nodes, distance_sensor_state)
return nodes[1] |
Load the ir transceiver state. | def ir_transceiver_state_fixture() -> dict:
"""Load the ir transceiver state."""
return load_nodes_state("ir_transceiver_state.json") |
Load the ir transceiver child node. | def ir_transceiver(
gateway_nodes: dict[int, Sensor], ir_transceiver_state: dict
) -> Sensor:
"""Load the ir transceiver child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(ir_transceiver_state))
return nodes[1] |
Load the relay node state. | def relay_node_state_fixture() -> dict:
"""Load the relay node state."""
return load_nodes_state("relay_node_state.json") |
Load the relay child node. | def relay_node(gateway_nodes: dict[int, Sensor], relay_node_state: dict) -> Sensor:
"""Load the relay child node."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(relay_node_state))
return nodes[1] |
Load the temperature sensor state. | def temperature_sensor_state_fixture() -> dict:
"""Load the temperature sensor state."""
return load_nodes_state("temperature_sensor_state.json") |
Load the temperature sensor. | def temperature_sensor(
gateway_nodes: dict[int, Sensor], temperature_sensor_state: dict
) -> Sensor:
"""Load the temperature sensor."""
nodes = update_gateway_nodes(gateway_nodes, temperature_sensor_state)
return nodes[1] |
Load the text node state. | def text_node_state_fixture() -> dict:
"""Load the text node state."""
return load_nodes_state("text_node_state.json") |
Load the text child node. | def text_node(gateway_nodes: dict[int, Sensor], text_node_state: dict) -> Sensor:
"""Load the text child node."""
nodes = update_gateway_nodes(gateway_nodes, text_node_state)
return nodes[1] |
Load the battery sensor state. | def battery_sensor_state_fixture() -> dict:
"""Load the battery sensor state."""
return load_nodes_state("battery_sensor_state.json") |
Load the battery sensor. | def battery_sensor(
gateway_nodes: dict[int, Sensor], battery_sensor_state: dict
) -> Sensor:
"""Load the battery sensor."""
nodes = update_gateway_nodes(gateway_nodes, deepcopy(battery_sensor_state))
return nodes[1] |
Test windows serial port. | def test_is_serial_port_windows(
hass: HomeAssistant, port: str, expect_valid: bool
) -> None:
"""Test windows serial port."""
with patch("sys.platform", "win32"):
try:
is_serial_port(port)
except vol.Invalid:
assert not expect_valid
else:
assert expect_valid |
Override async_setup_entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.mystrom.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry |
Create and add a config entry. | def config_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Create and add a config entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=DEVICE_MAC,
data={CONF_HOST: "1.1.1.1"},
title=DEVICE_NAME,
)
config_entry.add_to_hass(hass)
return config_entry |
Return default device response. | def get_default_device_response(device_type: int | None) -> dict[str, Any]:
"""Return default device response."""
response = {
"version": "2.59.32",
"mac": "6001940376EB",
"ssid": "personal",
"ip": "192.168.0.23",
"mask": "255.255.255.0",
"gw": "192.168.0.1",
"dns": "192.168.0.1",
"static": False,
"connected": True,
"signal": 94,
}
if device_type is not None:
response["type"] = device_type
return response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.