response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Call any service on entity. | def call_service(hass, service, ent):
"""Call any service on entity."""
return hass.services.async_call(
cover.DOMAIN, service, {ATTR_ENTITY_ID: ent.entity_id}, blocking=True
) |
Set a position value to a cover. | def set_cover_position(ent, position) -> None:
"""Set a position value to a cover."""
ent._values["current_cover_position"] = position |
Set the state of a cover. | def set_state(ent, state) -> None:
"""Set the state of a cover."""
ent._values["state"] = state |
Return if the cover is closed based on the statemachine. | def is_open(hass, ent):
"""Return if the cover is closed based on the statemachine."""
return hass.states.is_state(ent.entity_id, STATE_OPEN) |
Return if the cover is closed based on the statemachine. | def is_opening(hass, ent):
"""Return if the cover is closed based on the statemachine."""
return hass.states.is_state(ent.entity_id, STATE_OPENING) |
Return if the cover is closed based on the statemachine. | def is_closed(hass, ent):
"""Return if the cover is closed based on the statemachine."""
return hass.states.is_state(ent.entity_id, STATE_CLOSED) |
Return if the cover is closed based on the statemachine. | def is_closing(hass, ent):
"""Return if the cover is closed based on the statemachine."""
return hass.states.is_state(ent.entity_id, STATE_CLOSING) |
Test module.__all__ is correctly set. | def test_all() -> None:
"""Test module.__all__ is correctly set."""
help_test_all(cover) |
Test deprecated constants. | def test_deprecated_constants(
caplog: pytest.LogCaptureFixture,
enum: Enum,
constant_prefix: str,
) -> None:
"""Test deprecated constants."""
import_and_test_deprecated_constant_enum(
caplog, cover, enum, constant_prefix, "2025.1"
) |
Test deprecated supported features ints. | def test_deprecated_supported_features_ints(caplog: pytest.LogCaptureFixture) -> None:
"""Test deprecated supported features ints."""
class MockCoverEntity(cover.CoverEntity):
_attr_supported_features = 1
entity = MockCoverEntity()
assert entity.supported_features is cover.CoverEntityFeature(1)
assert "MockCoverEntity" in caplog.text
assert "is using deprecated supported features values" in caplog.text
assert "Instead it should use" in caplog.text
assert "CoverEntityFeature.OPEN" in caplog.text
caplog.clear()
assert entity.supported_features is cover.CoverEntityFeature(1)
assert "is using deprecated supported features values" not in caplog.text |
Return the default mocked config entry. | def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="CPU Speed",
domain=DOMAIN,
data={},
unique_id=DOMAIN,
) |
Return a mocked get_cpu_info.
It is only used to check truthy or falsy values, so it is mocked
to return True. | def mock_cpuinfo_config_flow() -> Generator[MagicMock, None, None]:
"""Return a mocked get_cpu_info.
It is only used to check truthy or falsy values, so it is mocked
to return True.
"""
with patch(
"homeassistant.components.cpuspeed.config_flow.cpuinfo.get_cpu_info",
return_value=True,
) as cpuinfo_mock:
yield cpuinfo_mock |
Mock setting up a config entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Mock setting up a config entry."""
with patch(
"homeassistant.components.cpuspeed.async_setup_entry", return_value=True
) as mock_setup:
yield mock_setup |
Return a mocked get_cpu_info. | def mock_cpuinfo() -> Generator[MagicMock, None, None]:
"""Return a mocked get_cpu_info."""
info = {
"hz_actual": (3200000001, 0),
"arch_string_raw": "aargh",
"brand_raw": "Intel Ryzen 7",
"hz_advertised": (3600000001, 0),
}
with patch(
"homeassistant.components.cpuspeed.cpuinfo.get_cpu_info",
return_value=info,
) as cpuinfo_mock:
yield cpuinfo_mock |
Mock Crownstone entry setup. | def crownstone_setup() -> MockFixture:
"""Mock Crownstone entry setup."""
with patch(
"homeassistant.components.crownstone.async_setup_entry", return_value=True
) as setup_mock:
yield setup_mock |
Mock pyserial comports. | def usb_comports() -> MockFixture:
"""Mock pyserial comports."""
with patch(
"serial.tools.list_ports.comports",
MagicMock(return_value=[get_mocked_com_port()]),
) as comports_mock:
yield comports_mock |
Mock pyserial comports. | def usb_comports_none_types() -> MockFixture:
"""Mock pyserial comports."""
with patch(
"serial.tools.list_ports.comports",
MagicMock(return_value=[get_mocked_com_port_none_types()]),
) as comports_mock:
yield comports_mock |
Mock usb serial path. | def usb_path() -> MockFixture:
"""Mock usb serial path."""
with patch(
"homeassistant.components.usb.get_serial_by_id",
return_value="/dev/serial/by-id/crownstone-usb",
) as usb_path_mock:
yield usb_path_mock |
Get a mocked CrownstoneEntryManager instance. | def get_mocked_crownstone_entry_manager(mocked_cloud: MagicMock):
"""Get a mocked CrownstoneEntryManager instance."""
mocked_entry_manager = MagicMock()
mocked_entry_manager.async_setup = AsyncMock(return_value=True)
mocked_entry_manager.cloud = mocked_cloud
return mocked_entry_manager |
Return a mocked Crownstone Cloud instance. | def get_mocked_crownstone_cloud(spheres: dict[str, MagicMock] | None = None):
"""Return a mocked Crownstone Cloud instance."""
mock_cloud = MagicMock()
mock_cloud.async_initialize = AsyncMock()
mock_cloud.cloud_data = Spheres(MagicMock(), "account_id")
mock_cloud.cloud_data.data = spheres
return mock_cloud |
Return a dict with mocked sphere instances. | def create_mocked_spheres(amount: int) -> dict[str, MagicMock]:
"""Return a dict with mocked sphere instances."""
spheres: dict[str, MagicMock] = {}
for i in range(amount):
spheres[f"sphere_id_{i}"] = MagicMock()
spheres[f"sphere_id_{i}"].name = f"sphere_name_{i}"
spheres[f"sphere_id_{i}"].cloud_id = f"sphere_id_{i}"
return spheres |
Mock of a serial port. | def get_mocked_com_port():
"""Mock of a serial port."""
port = ListPortInfo("/dev/ttyUSB1234")
port.device = "/dev/ttyUSB1234"
port.serial_number = "1234567"
port.manufacturer = "crownstone"
port.description = "crownstone dongle - crownstone dongle"
port.vid = 1234
port.pid = 5678
return port |
Mock of a serial port with NoneTypes. | def get_mocked_com_port_none_types():
"""Mock of a serial port with NoneTypes."""
port = ListPortInfo("/dev/ttyUSB1234")
port.device = "/dev/ttyUSB1234"
port.serial_number = None
port.manufacturer = None
port.description = "crownstone dongle - crownstone dongle"
port.vid = None
port.pid = None
return port |
Set a result for the entry data for comparison. | def create_mocked_entry_data_conf(email: str, password: str):
"""Set a result for the entry data for comparison."""
mock_data: dict[str, str | None] = {}
mock_data[CONF_EMAIL] = email
mock_data[CONF_PASSWORD] = password
return mock_data |
Set a result for the entry options for comparison. | def create_mocked_entry_options_conf(usb_path: str | None, usb_sphere: str | None):
"""Set a result for the entry options for comparison."""
mock_options: dict[str, str | None] = {}
mock_options[CONF_USB_PATH] = usb_path
mock_options[CONF_USB_SPHERE] = usb_sphere
return mock_options |
Mock pydaikin. | def mock_daikin():
"""Mock pydaikin."""
async def mock_daikin_factory(*args, **kwargs):
"""Mock the init function in pydaikin."""
return Appliance
with patch("homeassistant.components.daikin.config_flow.Appliance") as Appliance:
type(Appliance).mac = PropertyMock(return_value="AABBCCDDEEFF")
Appliance.factory.side_effect = mock_daikin_factory
yield Appliance |
Mock pydaikin Discovery. | def mock_daikin_discovery():
"""Mock pydaikin Discovery."""
with patch("homeassistant.components.daikin.config_flow.Discovery") as Discovery:
Discovery().poll.return_value = {
"127.0.01": {"mac": "AABBCCDDEEFF", "id": "test"}
}.values()
yield Discovery |
Mock pydaikin. | def mock_daikin():
"""Mock pydaikin."""
async def mock_daikin_factory(*args, **kwargs):
"""Mock the init function in pydaikin."""
return Appliance
with patch("homeassistant.components.daikin.Appliance") as Appliance:
Appliance.factory.side_effect = mock_daikin_factory
type(Appliance).update_status = AsyncMock()
type(Appliance).device_ip = PropertyMock(return_value=HOST)
type(Appliance).inside_temperature = PropertyMock(return_value=22)
type(Appliance).target_temperature = PropertyMock(return_value=22)
type(Appliance).zones = PropertyMock(return_value=[("Zone 1", "0", 0)])
type(Appliance).fan_rate = PropertyMock(return_value=[])
type(Appliance).swing_modes = PropertyMock(return_value=[])
yield Appliance |
Check no decimal are kept when target temp is an integer. | def test_int_conversion() -> None:
"""Check no decimal are kept when target temp is an integer."""
formatted = format_target_temperature("16")
assert formatted == "16" |
Check 1 decimal is kept when target temp is a decimal. | def test_rounding() -> None:
"""Check 1 decimal is kept when target temp is a decimal."""
formatted = format_target_temperature("16.1")
assert formatted == "16"
formatted = format_target_temperature("16.3")
assert formatted == "16.5"
formatted = format_target_temperature("16.65")
assert formatted == "16.5"
formatted = format_target_temperature("16.9")
assert formatted == "17" |
Mock debugpy lib. | def mock_debugpy():
"""Mock debugpy lib."""
with patch("homeassistant.components.debugpy.debugpy") as mocked_debugpy:
yield mocked_debugpy |
No real websocket allowed. | def mock_deconz_websocket():
"""No real websocket allowed."""
with patch("pydeconz.gateway.WSClient") as mock:
async def make_websocket_call(data: dict | None = None, state: str = ""):
"""Generate a websocket call."""
pydeconz_gateway_session_handler = mock.call_args[0][3]
if data:
mock.return_value.data = data
await pydeconz_gateway_session_handler(signal=Signal.DATA)
elif state:
mock.return_value.state = state
await pydeconz_gateway_session_handler(signal=Signal.CONNECTION_STATE)
else:
raise NotImplementedError
yield make_websocket_call |
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 automation calls to a mock service. | def automation_calls(hass):
"""Track automation calls to a mock service."""
return async_mock_service(hass, "test", "automation") |
Mock a deCONZ get request. | def mock_deconz_request(aioclient_mock, config, data):
"""Mock a deCONZ get request."""
host = config[CONF_HOST]
port = config[CONF_PORT]
api_key = config[CONF_API_KEY]
aioclient_mock.get(
f"http://{host}:{port}/api/{api_key}",
json=deepcopy(data),
headers={"content-type": CONTENT_TYPE_JSON},
) |
Mock a deCONZ put request. | def mock_deconz_put_request(aioclient_mock, config, path):
"""Mock a deCONZ put request."""
host = config[CONF_HOST]
port = config[CONF_PORT]
api_key = config[CONF_API_KEY]
aioclient_mock.put(
f"http://{host}:{port}/api/{api_key}{path}",
json={},
headers={"content-type": CONTENT_TYPE_JSON},
) |
Auto mock zeroconf. | def default_config_mock_async_zeroconf(mock_async_zeroconf):
"""Auto mock zeroconf.""" |
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.""" |
Mock ssdp. | def mock_ssdp():
"""Mock ssdp."""
with (
patch("homeassistant.components.ssdp.Scanner.async_scan"),
patch("homeassistant.components.ssdp.Server.async_start"),
patch("homeassistant.components.ssdp.Server.async_stop"),
):
yield |
Mock recorder url. | def recorder_url_mock():
"""Mock recorder url."""
with patch("homeassistant.components.recorder.DEFAULT_URL", "sqlite://"):
yield |
Mock an api. | def mock_deluge_api():
"""Mock an api."""
with (
patch("deluge_client.client.DelugeRPCClient.connect"),
patch("deluge_client.client.DelugeRPCClient._create_socket"),
):
yield |
Mock an api. | def mock_api_connection_error():
"""Mock an api."""
with (
patch(
"deluge_client.client.DelugeRPCClient.connect",
side_effect=ConnectionRefusedError("111: Connection refused"),
),
patch("deluge_client.client.DelugeRPCClient._create_socket"),
):
yield |
Mock an api. | def mock_api_unknown_error():
"""Mock an api."""
with (
patch("deluge_client.client.DelugeRPCClient.connect", side_effect=Exception),
patch("deluge_client.client.DelugeRPCClient._create_socket"),
):
yield |
Mock deluge entry setup. | def deluge_setup_fixture():
"""Mock deluge entry setup."""
with patch("homeassistant.components.deluge.async_setup_entry", return_value=True):
yield |
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.""" |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_PUSH)
assert state
assert state.state == STATE_UNKNOWN |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_CLIMATE)
assert state.state == HVACMode.COOL
assert state.attributes.get(ATTR_TEMPERATURE) == 21
assert state.attributes.get(ATTR_CURRENT_TEMPERATURE) == 22
assert state.attributes.get(ATTR_FAN_MODE) == "on_high"
assert state.attributes.get(ATTR_HUMIDITY) == 67.4
assert state.attributes.get(ATTR_CURRENT_HUMIDITY) == 54.2
assert state.attributes.get(ATTR_SWING_MODE) == "off"
assert state.attributes.get(ATTR_HVAC_MODES) == [
HVACMode.OFF,
HVACMode.HEAT,
HVACMode.COOL,
HVACMode.AUTO,
HVACMode.DRY,
HVACMode.FAN_ONLY,
] |
Test the setup with default parameters. | def test_default_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with default parameters."""
state = hass.states.get(ENTITY_CLIMATE)
assert state.attributes.get(ATTR_MIN_TEMP) == 7
assert state.attributes.get(ATTR_MAX_TEMP) == 35
assert state.attributes.get(ATTR_MIN_HUMIDITY) == 30
assert state.attributes.get(ATTR_MAX_HUMIDITY) == 99 |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_DATE)
assert state.state == "2020-01-01" |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_DATETIME)
assert state.state == "2020-01-01T12:00:00+00:00" |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_DEHUMIDIFIER)
assert state.state == STATE_ON
assert state.attributes.get(ATTR_HUMIDITY) == 54.2
assert state.attributes.get(ATTR_CURRENT_HUMIDITY) == 59.4
assert state.attributes.get(ATTR_ACTION) == "drying" |
Test the setup with default parameters. | def test_default_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with default parameters."""
state = hass.states.get(ENTITY_DEHUMIDIFIER)
assert state.attributes.get(ATTR_MIN_HUMIDITY) == 0
assert state.attributes.get(ATTR_MAX_HUMIDITY) == 100 |
Mock history component loaded. | def mock_history(hass):
"""Mock history component loaded."""
hass.config.components.add("history") |
Prevent device tracker from creating known devices file. | def mock_device_tracker_update_config():
"""Prevent device tracker from creating known devices file."""
with patch("homeassistant.components.device_tracker.legacy.update_config"):
yield |
Auto use the disable_platforms fixture. | def autouse_disable_platforms(disable_platforms):
"""Auto use the disable_platforms fixture."""
with patch(
"homeassistant.components.demo.COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM",
[Platform.MEDIA_PLAYER],
):
yield |
Mock demo YouTube player media seek. | def media_player_media_seek_fixture():
"""Mock demo YouTube player media seek."""
with patch(
"homeassistant.components.demo.media_player.DemoYoutubePlayer.media_seek",
autospec=True,
) as seek:
yield seek |
Enable only the notify platform. | def notify_only() -> Generator[None, None]:
"""Enable only the notify platform."""
with patch(
"homeassistant.components.demo.COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM",
[Platform.NOTIFY],
):
yield |
Fixture that catches notify events. | def events(hass: HomeAssistant) -> list[Event]:
"""Fixture that catches notify events."""
return async_capture_events(hass, demo.EVENT_NOTIFY) |
Fixture to calls. | def calls():
"""Fixture to calls."""
return [] |
Fixture to record calls. | def record_calls(calls):
"""Fixture to record calls."""
@callback
def record_calls(*args):
"""Record calls."""
calls.append(args)
return record_calls |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_VOLUME)
assert state.state == "42.0" |
Test the setup with default parameters. | def test_default_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with default parameters."""
state = hass.states.get(ENTITY_VOLUME)
assert state.attributes.get(ATTR_MIN) == 0.0
assert state.attributes.get(ATTR_MAX) == 100.0
assert state.attributes.get(ATTR_STEP) == 1.0
assert state.attributes.get(ATTR_MODE) == NumberMode.SLIDER
state = hass.states.get(ENTITY_PWM)
assert state.attributes.get(ATTR_MIN) == 0.0
assert state.attributes.get(ATTR_MAX) == 1.0
assert state.attributes.get(ATTR_STEP) == 0.01
assert state.attributes.get(ATTR_MODE) == NumberMode.BOX
state = hass.states.get(ENTITY_LARGE_RANGE)
assert state.attributes.get(ATTR_MIN) == 1.0
assert state.attributes.get(ATTR_MAX) == 1000.0
assert state.attributes.get(ATTR_STEP) == 1.0
assert state.attributes.get(ATTR_MODE) == NumberMode.AUTO
state = hass.states.get(ENTITY_SMALL_RANGE)
assert state.attributes.get(ATTR_MIN) == 1.0
assert state.attributes.get(ATTR_MAX) == 255.0
assert state.attributes.get(ATTR_STEP) == 1.0
assert state.attributes.get(ATTR_MODE) == NumberMode.AUTO |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_SPEED)
assert state
assert state.state == "ridiculous_speed"
assert state.attributes.get(ATTR_OPTIONS) == [
"light_speed",
"ridiculous_speed",
"ludicrous_speed",
] |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_SIREN)
assert state.state == STATE_ON
assert ATTR_AVAILABLE_TONES not in state.attributes |
Test the setup with all parameters. | def test_all_setup_params(hass: HomeAssistant) -> None:
"""Test the setup with all parameters."""
state = hass.states.get(ENTITY_SIREN_WITH_ALL_FEATURES)
assert state.attributes.get(ATTR_AVAILABLE_TONES) == ["fire", "alarm"] |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_TEXT)
assert state.state == "Hello world"
assert state.attributes[ATTR_MIN] == 0
assert state.attributes[ATTR_MAX] == MAX_LENGTH_STATE_STATE
assert state.attributes[ATTR_PATTERN] is None
assert state.attributes[ATTR_MODE] == "text" |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get(ENTITY_TIME)
assert state.state == "12:00:00" |
Test the initial parameters. | def test_setup_params(hass: HomeAssistant) -> None:
"""Test the initial parameters."""
state = hass.states.get("update.demo_update_no_install")
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_TITLE] == "Awesomesoft Inc."
assert state.attributes[ATTR_INSTALLED_VERSION] == "1.0.0"
assert state.attributes[ATTR_LATEST_VERSION] == "1.0.1"
assert (
state.attributes[ATTR_RELEASE_SUMMARY] == "Awesome update, fixing everything!"
)
assert state.attributes[ATTR_RELEASE_URL] == "https://www.example.com/release/1.0.1"
assert (
state.attributes[ATTR_ENTITY_PICTURE]
== "https://brands.home-assistant.io/_/demo/icon.png"
)
state = hass.states.get("update.demo_no_update")
assert state
assert state.state == STATE_OFF
assert state.attributes[ATTR_TITLE] == "AdGuard Home"
assert state.attributes[ATTR_INSTALLED_VERSION] == "1.0.0"
assert state.attributes[ATTR_LATEST_VERSION] == "1.0.0"
assert state.attributes[ATTR_RELEASE_SUMMARY] is None
assert state.attributes[ATTR_RELEASE_URL] is None
assert (
state.attributes[ATTR_ENTITY_PICTURE]
== "https://brands.home-assistant.io/_/demo/icon.png"
)
state = hass.states.get("update.demo_add_on")
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_TITLE] == "AdGuard Home"
assert state.attributes[ATTR_INSTALLED_VERSION] == "1.0.0"
assert state.attributes[ATTR_LATEST_VERSION] == "1.0.1"
assert (
state.attributes[ATTR_RELEASE_SUMMARY] == "Awesome update, fixing everything!"
)
assert state.attributes[ATTR_RELEASE_URL] == "https://www.example.com/release/1.0.1"
assert (
state.attributes[ATTR_ENTITY_PICTURE]
== "https://brands.home-assistant.io/_/demo/icon.png"
)
state = hass.states.get("update.demo_living_room_bulb_update")
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_TITLE] == "Philips Lamps Firmware"
assert state.attributes[ATTR_INSTALLED_VERSION] == "1.93.3"
assert state.attributes[ATTR_LATEST_VERSION] == "1.94.2"
assert state.attributes[ATTR_RELEASE_SUMMARY] == "Added support for effects"
assert (
state.attributes[ATTR_RELEASE_URL] == "https://www.example.com/release/1.93.3"
)
assert state.attributes[ATTR_DEVICE_CLASS] == UpdateDeviceClass.FIRMWARE
assert (
state.attributes[ATTR_ENTITY_PICTURE]
== "https://brands.home-assistant.io/_/demo/icon.png"
)
state = hass.states.get("update.demo_update_with_progress")
assert state
assert state.state == STATE_ON
assert state.attributes[ATTR_TITLE] == "Philips Lamps Firmware"
assert state.attributes[ATTR_INSTALLED_VERSION] == "1.93.3"
assert state.attributes[ATTR_LATEST_VERSION] == "1.94.2"
assert state.attributes[ATTR_RELEASE_SUMMARY] == "Added support for effects"
assert (
state.attributes[ATTR_RELEASE_URL] == "https://www.example.com/release/1.93.3"
)
assert state.attributes[ATTR_DEVICE_CLASS] == UpdateDeviceClass.FIRMWARE
assert (
state.attributes[ATTR_ENTITY_PICTURE]
== "https://brands.home-assistant.io/_/demo/icon.png"
) |
Mock denonavr connection and entry setup. | def denonavr_connect_fixture():
"""Mock denonavr connection and entry setup."""
with (
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.async_setup",
return_value=None,
),
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.async_update",
return_value=None,
),
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.support_sound_mode",
return_value=True,
),
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.name",
TEST_NAME,
),
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.model_name",
TEST_MODEL,
),
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.serial_number",
TEST_SERIALNUMBER,
),
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.manufacturer",
TEST_MANUFACTURER,
),
patch(
"homeassistant.components.denonavr.receiver.DenonAVR.receiver_type",
TEST_RECEIVER_TYPE,
),
patch(
"homeassistant.components.denonavr.async_setup_entry",
return_value=True,
),
):
yield |
Patch of client library for tests. | def client_fixture():
"""Patch of client library for tests."""
with (
patch(
"homeassistant.components.denonavr.receiver.DenonAVR",
autospec=True,
) as mock_client_class,
patch("homeassistant.components.denonavr.config_flow.denonavr.async_discover"),
):
mock_client_class.return_value.name = TEST_NAME
mock_client_class.return_value.model_name = TEST_MODEL
mock_client_class.return_value.serial_number = TEST_SERIALNUMBER
mock_client_class.return_value.manufacturer = TEST_MANUFACTURER
mock_client_class.return_value.receiver_type = TEST_RECEIVER_TYPE
mock_client_class.return_value.zone = TEST_ZONE
mock_client_class.return_value.input_func_list = []
mock_client_class.return_value.sound_mode_list = []
mock_client_class.return_value.zones = {"Main": mock_client_class.return_value}
yield mock_client_class.return_value |
Get suggested value for key in voluptuous schema. | def get_suggested(schema, key):
"""Get suggested value for key in voluptuous schema."""
for k in schema:
if k == key:
if k.description is None or "suggested_value" not in k.description:
return None
return k.description["suggested_value"]
# Wanted key absent from schema
raise Exception |
Mock the Devialet connection for Home Assistant. | def mock_unavailable(aioclient_mock: AiohttpClientMocker) -> None:
"""Mock the Devialet connection for Home Assistant."""
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_GENERAL_INFO}", exc=ServerTimeoutError
) |
Mock the Devialet connection for Home Assistant. | def mock_idle(aioclient_mock: AiohttpClientMocker) -> None:
"""Mock the Devialet connection for Home Assistant."""
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_GENERAL_INFO}",
text=load_fixture("general_info.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_CURRENT_SOURCE}",
exc=ServerTimeoutError,
) |
Mock the Devialet connection for Home Assistant. | def mock_playing(aioclient_mock: AiohttpClientMocker) -> None:
"""Mock the Devialet connection for Home Assistant."""
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_GENERAL_INFO}",
text=load_fixture("general_info.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_CURRENT_SOURCE}",
text=load_fixture("source_state.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_SOURCES}",
text=load_fixture("sources.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_VOLUME}",
text=load_fixture("volume.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_NIGHT_MODE}",
text=load_fixture("night_mode.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_EQUALIZER}",
text=load_fixture("equalizer.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
)
aioclient_mock.get(
f"http://{HOST}{UrlSuffix.GET_CURRENT_POSITION}",
text=load_fixture("current_position.json", DOMAIN),
headers={"Content-Type": CONTENT_TYPE_JSON},
) |
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.""" |
Set up a mock integration with device automation support. | def fake_integration(hass):
"""Set up a mock integration with device automation support."""
DOMAIN = "fake_integration"
hass.config.components.add(DOMAIN)
async def _async_get_actions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device actions."""
return await toggle_entity.async_get_actions(hass, device_id, DOMAIN)
async def _async_get_conditions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device conditions."""
return await toggle_entity.async_get_conditions(hass, device_id, DOMAIN)
async def _async_get_triggers(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device triggers."""
return await toggle_entity.async_get_triggers(hass, device_id, DOMAIN)
mock_platform(
hass,
f"{DOMAIN}.device_action",
Mock(
ACTION_SCHEMA=toggle_entity.ACTION_SCHEMA.extend(
{vol.Required("domain"): DOMAIN}
),
async_get_actions=_async_get_actions,
spec=["ACTION_SCHEMA", "async_get_actions"],
),
)
mock_platform(
hass,
f"{DOMAIN}.device_condition",
Mock(
CONDITION_SCHEMA=toggle_entity.CONDITION_SCHEMA.extend(
{vol.Required("domain"): DOMAIN}
),
async_get_conditions=_async_get_conditions,
spec=["CONDITION_SCHEMA", "async_get_conditions"],
),
)
mock_platform(
hass,
f"{DOMAIN}.device_trigger",
Mock(
TRIGGER_SCHEMA=vol.All(
toggle_entity.TRIGGER_SCHEMA,
vol.Schema({vol.Required("domain"): DOMAIN}, extra=vol.ALLOW_EXTRA),
),
async_get_triggers=_async_get_triggers,
spec=["TRIGGER_SCHEMA", "async_get_triggers"],
),
) |
Track calls to a mock service. | def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") |
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):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") |
Call service to notify you see device. | def async_see(
hass: HomeAssistant,
mac: str | None = None,
dev_id: str | None = None,
host_name: str | None = None,
location_name: str | None = None,
gps: GPSType | None = None,
gps_accuracy=None,
battery: int | None = None,
attributes: dict | None = None,
):
"""Call service to notify you see device."""
data = {
key: value
for key, value in (
(ATTR_MAC, mac),
(ATTR_DEV_ID, dev_id),
(ATTR_HOST_NAME, host_name),
(ATTR_LOCATION_NAME, location_name),
(ATTR_GPS, gps),
(ATTR_GPS_ACCURACY, gps_accuracy),
(ATTR_BATTERY, battery),
)
if value is not None
}
if attributes:
data[ATTR_ATTRIBUTES] = attributes
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_SEE, data)) |
Mock legacy device tracker platform setup. | def mock_legacy_device_tracker_setup(
hass: HomeAssistant, legacy_device_scanner: MockScanner
) -> None:
"""Mock legacy device tracker platform setup."""
async def _async_get_scanner(hass, config) -> MockScanner:
"""Return the test scanner."""
return legacy_device_scanner
mocked_platform = MockPlatform()
mocked_platform.async_get_scanner = _async_get_scanner
mock_platform(hass, "test.device_tracker", mocked_platform) |
Mock config flow. | def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]:
"""Mock config flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
with mock_config_flow(TEST_DOMAIN, MockFlow):
yield |
Fixture to set up a mock integration. | def mock_setup_integration(hass: HomeAssistant) -> None:
"""Fixture to set up a mock integration."""
async def async_setup_entry_init(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Set up test config entry."""
await hass.config_entries.async_forward_entry_setups(
config_entry, [Platform.DEVICE_TRACKER]
)
return True
async def async_unload_entry_init(
hass: HomeAssistant,
config_entry: ConfigEntry,
) -> bool:
await hass.config_entries.async_unload_platforms(
config_entry, [Platform.DEVICE_TRACKER]
)
return True
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
mock_integration(
hass,
MockModule(
TEST_DOMAIN,
async_setup_entry=async_setup_entry_init,
async_unload_entry=async_unload_entry_init,
),
) |
Return the config entry used for the tests. | def config_entry_fixture(hass: HomeAssistant) -> MockConfigEntry:
"""Return the config entry used for the tests."""
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
config_entry.add_to_hass(hass)
return config_entry |
Return the entity_id of the entity for the test. | def entity_id_fixture() -> str:
"""Return the entity_id of the entity for the test."""
return "device_tracker.entity1" |
Return the battery level of the entity for the test. | def battery_level_fixture() -> int | None:
"""Return the battery level of the entity for the test."""
return None |
Return the location_name of the entity for the test. | def location_name_fixture() -> str | None:
"""Return the location_name of the entity for the test."""
return None |
Return the latitude of the entity for the test. | def latitude_fixture() -> float | None:
"""Return the latitude of the entity for the test."""
return None |
Return the longitude of the entity for the test. | def longitude_fixture() -> float | None:
"""Return the longitude of the entity for the test."""
return None |
Create a test tracker entity. | def tracker_entity_fixture(
entity_id: str,
battery_level: int | None,
location_name: str | None,
latitude: float | None,
longitude: float | None,
) -> MockTrackerEntity:
"""Create a test tracker entity."""
entity = MockTrackerEntity(
battery_level=battery_level,
location_name=location_name,
latitude=latitude,
longitude=longitude,
)
entity.entity_id = entity_id
return entity |
Return the ip_address of the entity for the test. | def ip_address_fixture() -> str | None:
"""Return the ip_address of the entity for the test."""
return None |
Return the mac_address of the entity for the test. | def mac_address_fixture() -> str | None:
"""Return the mac_address of the entity for the test."""
return None |
Return the hostname of the entity for the test. | def hostname_fixture() -> str | None:
"""Return the hostname of the entity for the test."""
return None |
Return the unique_id of the entity for the test. | def unique_id_fixture() -> str | None:
"""Return the unique_id of the entity for the test."""
return None |
Create a test scanner entity. | def scanner_entity_fixture(
entity_id: str,
ip_address: str | None,
mac_address: str | None,
hostname: str | None,
unique_id: str | None,
) -> MockScannerEntity:
"""Create a test scanner entity."""
entity = MockScannerEntity(
ip_address=ip_address,
mac_address=mac_address,
hostname=hostname,
unique_id=unique_id,
)
entity.entity_id = entity_id
return entity |
Test coverage for base TrackerEntity class. | def test_tracker_entity() -> None:
"""Test coverage for base TrackerEntity class."""
entity = TrackerEntity()
with pytest.raises(NotImplementedError):
assert entity.source_type is None
assert entity.latitude is None
assert entity.longitude is None
assert entity.location_name is None
assert entity.state is None
assert entity.battery_level is None
assert entity.should_poll is False
assert entity.force_update is True
class MockEntity(TrackerEntity):
"""Mock tracker class."""
def __init__(self) -> None:
"""Initialize."""
self.is_polling = False
@property
def should_poll(self) -> bool:
"""Return False for the test entity."""
return self.is_polling
test_entity = MockEntity()
assert test_entity.force_update
test_entity.is_polling = True
assert not test_entity.force_update |
Test coverage for base ScannerEntity entity class. | def test_scanner_entity() -> None:
"""Test coverage for base ScannerEntity entity class."""
entity = ScannerEntity()
with pytest.raises(NotImplementedError):
assert entity.source_type is None
with pytest.raises(NotImplementedError):
assert entity.is_connected is None
with pytest.raises(NotImplementedError):
assert entity.state == STATE_NOT_HOME
assert entity.battery_level is None
assert entity.ip_address is None
assert entity.mac_address is None
assert entity.hostname is None
class MockEntity(ScannerEntity):
"""Mock scanner class."""
def __init__(self) -> None:
"""Initialize."""
self.mock_mac_address: str | None = None
@property
def mac_address(self) -> str | None:
"""Return the mac address of the device."""
return self.mock_mac_address
test_entity = MockEntity()
assert test_entity.unique_id is None
test_entity.mock_mac_address = TEST_MAC_ADDRESS
assert test_entity.unique_id == TEST_MAC_ADDRESS |
Test coverage for base BaseTrackerEntity entity class. | def test_base_tracker_entity() -> None:
"""Test coverage for base BaseTrackerEntity entity class."""
entity = BaseTrackerEntity()
with pytest.raises(NotImplementedError):
assert entity.source_type is None
assert entity.battery_level is None
with pytest.raises(NotImplementedError):
assert entity.state_attributes is None |
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):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.