response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Send the media player the command for play/pause. | def media_play_pause(hass, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command for play/pause."""
hass.add_job(async_media_play_pause, hass, entity_id) |
Send the media player the command for play/pause. | def media_play(hass, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command for play/pause."""
hass.add_job(async_media_play, hass, entity_id) |
Send the media player the command for pause. | def media_pause(hass, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command for pause."""
hass.add_job(async_media_pause, hass, entity_id) |
Send the media player the command for stop. | def media_stop(hass, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command for stop."""
hass.add_job(async_media_stop, hass, entity_id) |
Send the media player the command for next track. | def media_next_track(hass, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command for next track."""
hass.add_job(async_media_next_track, hass, entity_id) |
Send the media player the command for prev track. | def media_previous_track(hass, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command for prev track."""
hass.add_job(async_media_previous_track, hass, entity_id) |
Send the media player the command to seek in current playing media. | def media_seek(hass, position, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command to seek in current playing media."""
hass.add_job(async_media_seek, hass, position, entity_id) |
Send the media player the command for playing media. | def play_media(hass, media_type, media_id, entity_id=ENTITY_MATCH_ALL, enqueue=None):
"""Send the media player the command for playing media."""
hass.add_job(async_play_media, hass, media_type, media_id, entity_id, enqueue) |
Send the media player the command to select input source. | def select_source(hass, source, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command to select input source."""
hass.add_job(async_select_source, hass, source, entity_id) |
Send the media player the command for clear playlist. | def clear_playlist(hass, entity_id=ENTITY_MATCH_ALL):
"""Send the media player the command for clear playlist."""
hass.add_job(async_clear_playlist, hass, entity_id) |
Return a media player. | def player(hass, request):
"""Return a media player."""
return request.param(hass) |
Mock sign path. | def fixture_mock_sign_path():
"""Mock sign path."""
with patch(
"homeassistant.components.media_player.browse_media.async_sign_path",
side_effect=lambda _, url, _2: url + "?authSig=bla",
):
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.""" |
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") |
Test deprecated supported features ints. | def test_deprecated_supported_features_ints(caplog: pytest.LogCaptureFixture) -> None:
"""Test deprecated supported features ints."""
class MockMediaPlayerEntity(MediaPlayerEntity):
@property
def supported_features(self) -> int:
"""Return supported features."""
return 1
entity = MockMediaPlayerEntity()
assert entity.supported_features_compat is MediaPlayerEntityFeature(1)
assert "MockMediaPlayerEntity" in caplog.text
assert "is using deprecated supported features values" in caplog.text
assert "Instead it should use" in caplog.text
assert "MediaPlayerEntityFeature.PAUSE" in caplog.text
caplog.clear()
assert entity.supported_features_compat is MediaPlayerEntityFeature(1)
assert "is using deprecated supported features values" not in caplog.text |
Mock MELCloud device. | def mock_device():
"""Mock MELCloud device."""
with patch("homeassistant.components.melcloud.MelCloudDevice") as mock:
mock.name = "name"
mock.device.serial = 1234
mock.device.mac = "11:11:11:11:11:11"
yield mock |
Mock zone 1. | def mock_zone_1():
"""Mock zone 1."""
with patch("pymelcloud.atw_device.Zone") as mock:
mock.zone_index = 1
yield mock |
Mock zone 2. | def mock_zone_2():
"""Mock zone 2."""
with patch("pymelcloud.atw_device.Zone") as mock:
mock.zone_index = 2
yield mock |
Test unique id generation correctness. | def test_zone_unique_ids(mock_device, mock_zone_1, mock_zone_2) -> None:
"""Test unique id generation correctness."""
sensor_1 = AtwZoneSensor(
mock_device,
mock_zone_1,
ATW_ZONE_SENSORS[0], # room_temperature
)
assert sensor_1.unique_id == "1234-11:11:11:11:11:11-room_temperature"
sensor_2 = AtwZoneSensor(
mock_device,
mock_zone_2,
ATW_ZONE_SENSORS[0], # room_temperature
)
assert sensor_2.unique_id == "1234-11:11:11:11:11:11-room_temperature-zone-2" |
Mock pymelcloud login. | def mock_login():
"""Mock pymelcloud login."""
with patch(
"homeassistant.components.melcloud.config_flow.pymelcloud.login"
) as mock:
mock.return_value = "test-token"
yield mock |
Mock pymelcloud get_devices. | def mock_get_devices():
"""Mock pymelcloud get_devices."""
with patch(
"homeassistant.components.melcloud.config_flow.pymelcloud.get_devices"
) as mock:
mock.return_value = {
pymelcloud.DEVICE_TYPE_ATA: [],
pymelcloud.DEVICE_TYPE_ATW: [],
}
yield mock |
Mock RequestInfo to create ClientResponseErrors. | def mock_request_info():
"""Mock RequestInfo to create ClientResponseErrors."""
with patch("aiohttp.RequestInfo") as mock_ri:
mock_ri.return_value.real_url.return_value = ""
yield mock_ri |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Return a mock config entry. | def mock_config_entry(hass: HomeAssistant):
"""Return a mock config entry."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id=FAKE_ADDRESS_1,
data={CONF_ADDRESS: FAKE_ADDRESS_1},
)
entry.add_to_hass(hass)
return entry |
Return a mocked Melnor device. | def mock_melnor_device():
"""Return a mocked Melnor device."""
with patch("melnor_bluetooth.device.Device") as mock:
device = mock.return_value
device.connect = AsyncMock(return_value=True)
device.disconnect = AsyncMock(return_value=True)
device.fetch_state = AsyncMock(return_value=device)
device.push_state = AsyncMock(return_value=None)
device.battery_level = 80
device.mac = FAKE_ADDRESS_1
device.model = "test_model"
device.name = "test_melnor"
device.rssi = -50
device.zone1 = MockValve(0)
device.zone2 = MockValve(1)
device.zone3 = MockValve(2)
device.zone4 = MockValve(3)
device.__getitem__.side_effect = lambda key: getattr(device, key)
return device |
Patch async setup entry to return True. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Patch async setup entry to return True."""
with patch(
"homeassistant.components.melnor.async_setup_entry", return_value=True
) as mock_setup:
yield mock_setup |
Patch async_discovered_service_info a mocked device info. | def patch_async_discovered_service_info(
return_value: list[BluetoothServiceInfoBleak] = [FAKE_SERVICE_INFO_1],
):
"""Patch async_discovered_service_info a mocked device info."""
return patch(
"homeassistant.components.melnor.config_flow.async_discovered_service_info",
return_value=return_value,
) |
Patch async_ble_device_from_address to return a mocked BluetoothServiceInfoBleak. | def patch_async_ble_device_from_address(
return_value: BluetoothServiceInfoBleak | None = FAKE_SERVICE_INFO_1,
):
"""Patch async_ble_device_from_address to return a mocked BluetoothServiceInfoBleak."""
return patch(
"homeassistant.components.bluetooth.async_ble_device_from_address",
return_value=return_value,
) |
Patch melnor_bluetooth.device to return a mocked Melnor device. | def patch_melnor_device(device: Device = mock_melnor_device()):
"""Patch melnor_bluetooth.device to return a mocked Melnor device."""
return patch("homeassistant.components.melnor.Device", return_value=device) |
Patch async_register_callback to return True. | def patch_async_register_callback():
"""Patch async_register_callback to return True."""
return patch("homeassistant.components.bluetooth.async_register_callback") |
Meraki mock client. | def meraki_client(event_loop, hass, hass_client):
"""Meraki mock client."""
loop = event_loop
async def setup_and_wait():
result = await async_setup_component(
hass,
device_tracker.DOMAIN,
{
device_tracker.DOMAIN: {
CONF_PLATFORM: "meraki",
CONF_VALIDATOR: "validator",
CONF_SECRET: "secret",
}
},
)
await hass.async_block_till_done()
return result
assert loop.run_until_complete(setup_and_wait())
return loop.run_until_complete(hass_client()) |
Mock weather data. | def mock_weather():
"""Mock weather data."""
with patch("metno.MetWeatherData") as mock_data:
mock_data = mock_data.return_value
mock_data.fetching_data = AsyncMock(return_value=True)
mock_data.get_current_weather.return_value = {
"condition": "cloudy",
"temperature": 15,
"pressure": 100,
"humidity": 50,
"wind_speed": 10,
"wind_bearing": "NE",
"dew_point": 12.1,
}
mock_data.get_forecast.return_value = {}
yield mock_data |
Patch met setup entry. | def met_setup_fixture(request):
"""Patch met setup entry."""
if "disable_autouse_fixture" in request.keywords:
yield
else:
with patch("homeassistant.components.met.async_setup_entry", return_value=True):
yield |
Stub out services that makes requests. | def patch_requests():
"""Stub out services that makes requests."""
patch_client = patch("homeassistant.components.meteoclimatic.MeteoclimaticClient")
with patch_client:
yield |
Mock a successful client. | def mock_controller_client():
"""Mock a successful client."""
with patch(
"homeassistant.components.meteoclimatic.config_flow.MeteoclimaticClient",
update=False,
) as service_mock:
service_mock.return_value.get_data.return_value = {
"station_code": TEST_STATION_CODE
}
weather = service_mock.return_value.weather_at_station.return_value
weather.station.name = TEST_STATION_NAME
yield service_mock |
Prevent setup. | def mock_setup():
"""Prevent setup."""
with patch(
"homeassistant.components.meteoclimatic.async_setup_entry",
return_value=True,
):
yield |
Stub out services that makes requests. | def patch_requests():
"""Stub out services that makes requests."""
patch_client = patch("homeassistant.components.meteo_france.MeteoFranceClient")
with patch_client:
yield |
Mock a successful client. | def mock_controller_client_single():
"""Mock a successful client."""
with patch(
"homeassistant.components.meteo_france.config_flow.MeteoFranceClient",
update=False,
) as service_mock:
service_mock.return_value.search_places.return_value = [CITY_1]
yield service_mock |
Prevent setup. | def mock_setup():
"""Prevent setup."""
with patch(
"homeassistant.components.meteo_france.async_setup_entry",
return_value=True,
):
yield |
Mock a successful client. | def mock_controller_client_multiple():
"""Mock a successful client."""
with patch(
"homeassistant.components.meteo_france.config_flow.MeteoFranceClient",
update=False,
) as service_mock:
service_mock.return_value.search_places.return_value = [CITY_2, CITY_3]
yield service_mock |
Mock a successful client. | def mock_controller_client_empty():
"""Mock a successful client."""
with patch(
"homeassistant.components.meteo_france.config_flow.MeteoFranceClient",
update=False,
) as service_mock:
service_mock.return_value.search_places.return_value = []
yield service_mock |
Mock datapoint Manager with default values for testing in config_flow. | def mock_simple_manager_fail():
"""Mock datapoint Manager with default values for testing in config_flow."""
with patch("datapoint.Manager") as mock_manager:
instance = mock_manager.return_value
instance.get_nearest_forecast_site.side_effect = APIException()
instance.get_forecast_for_site.side_effect = APIException()
instance.latitude = None
instance.longitude = None
instance.site = None
instance.site_id = None
instance.site_name = None
instance.now = None
yield mock_manager |
Remove sensors. | def no_sensor():
"""Remove sensors."""
with patch(
"homeassistant.components.metoffice.sensor.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry |
Mock weather data. | def mock_weather():
"""Mock weather data."""
with patch("meteireann.WeatherData") as mock_data:
mock_data = mock_data.return_value
mock_data.fetching_data = AsyncMock(return_value=True)
mock_data.get_current_weather.return_value = {
"condition": "Cloud",
"temperature": 15,
"pressure": 100,
"humidity": 50,
"wind_speed": 10,
"wind_bearing": "NE",
}
mock_data.get_forecast.return_value = {}
yield mock_data |
Patch Met Éireann setup entry. | def met_setup_fixture():
"""Patch Met Éireann setup entry."""
with patch(
"homeassistant.components.met_eireann.async_setup_entry", return_value=True
):
yield |
Port fixture. | def port_fixture():
"""Port fixture."""
return mock.MagicMock() |
Sensor fixture. | def sensor_fixture(hass, port):
"""Sensor fixture."""
sensor = mfi.MfiSensor(port, hass)
sensor.hass = hass
return sensor |
Port fixture. | def port_fixture():
"""Port fixture."""
return mock.MagicMock() |
Switch fixture. | def switch_fixture(port):
"""Switch fixture."""
return mfi.MfiSwitch(port) |
Fixture to set the scopes present in the OAuth token. | def mock_scopes() -> list[str]:
"""Fixture to set the scopes present in the OAuth token."""
return SCOPES |
Fixture to set the oauth token expiration time. | def mock_expires_at() -> int:
"""Fixture to set the oauth token expiration time."""
return time.time() + 3600 |
Create YouTube entry in Home Assistant. | def mock_config_entry(expires_at: int, scopes: list[str]) -> MockConfigEntry:
"""Create YouTube entry in Home Assistant."""
return MockConfigEntry(
domain=DOMAIN,
title=TITLE,
unique_id=54321,
data={
"auth_implementation": DOMAIN,
"token": {
"access_token": "mock-access-token",
"refresh_token": "mock-refresh-token",
"expires_at": expires_at,
"scope": " ".join(scopes),
},
},
) |
Mock microbees. | def mock_microbees():
"""Mock microbees."""
devices_json = load_json_array_fixture("microbees/bees.json")
devices = [Bee.from_dict(device) for device in devices_json]
profile_json = load_json_object_fixture("microbees/profile.json")
profile = Profile.from_dict(profile_json)
mock = AsyncMock(spec=MicroBees)
mock.getBees.return_value = devices
mock.getMyProfile.return_value = profile
with (
patch(
"homeassistant.components.microbees.config_flow.MicroBees",
return_value=mock,
) as mock,
patch(
"homeassistant.components.microbees.MicroBees",
return_value=mock,
),
):
yield mock |
Mock the TTS cache dir with empty dir. | def mock_tts_cache_dir_autouse(mock_tts_cache_dir):
"""Mock the TTS cache dir with empty dir."""
return mock_tts_cache_dir |
Mock tts. | def mock_tts():
"""Mock tts."""
with patch(
"homeassistant.components.microsoft.tts.pycsspeechtts.TTSTranslator"
) as mock_tts:
mock_tts.return_value.speak.return_value = b""
yield mock_tts |
Test list of supported languages. | def test_supported_languages() -> None:
"""Test list of supported languages."""
for lang in ["en-us", "fa-ir", "en-gb"]:
assert lang in SUPPORTED_LANGUAGES
assert "en-US" not in SUPPORTED_LANGUAGES
for lang in [
"en",
"en-uk",
"english",
"english (united states)",
"jennyneural",
"en-us-jennyneural",
]:
assert lang not in {s.lower() for s in SUPPORTED_LANGUAGES}
assert len(SUPPORTED_LANGUAGES) > 100 |
Create a new person group.
This is a legacy helper method. Do not use it for new tests. | def create_group(hass, name):
"""Create a new person group.
This is a legacy helper method. Do not use it for new tests.
"""
data = {ATTR_NAME: name}
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_CREATE_GROUP, data)) |
Delete a person group.
This is a legacy helper method. Do not use it for new tests. | def delete_group(hass, name):
"""Delete a person group.
This is a legacy helper method. Do not use it for new tests.
"""
data = {ATTR_NAME: name}
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_DELETE_GROUP, data)) |
Train a person group.
This is a legacy helper method. Do not use it for new tests. | def train_group(hass, group):
"""Train a person group.
This is a legacy helper method. Do not use it for new tests.
"""
data = {ATTR_GROUP: group}
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_TRAIN_GROUP, data)) |
Create a person in a group.
This is a legacy helper method. Do not use it for new tests. | def create_person(hass, group, name):
"""Create a person in a group.
This is a legacy helper method. Do not use it for new tests.
"""
data = {ATTR_GROUP: group, ATTR_NAME: name}
hass.async_create_task(
hass.services.async_call(DOMAIN, SERVICE_CREATE_PERSON, data)
) |
Delete a person in a group.
This is a legacy helper method. Do not use it for new tests. | def delete_person(hass, group, name):
"""Delete a person in a group.
This is a legacy helper method. Do not use it for new tests.
"""
data = {ATTR_GROUP: group, ATTR_NAME: name}
hass.async_create_task(
hass.services.async_call(DOMAIN, SERVICE_DELETE_PERSON, data)
) |
Add a new face picture to a person.
This is a legacy helper method. Do not use it for new tests. | def face_person(hass, group, person, camera_entity):
"""Add a new face picture to a person.
This is a legacy helper method. Do not use it for new tests.
"""
data = {ATTR_GROUP: group, ATTR_PERSON: person, ATTR_CAMERA_ENTITY: camera_entity}
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_FACE_PERSON, data)) |
Mock update store. | def mock_update():
"""Mock update store."""
with patch(
"homeassistant.components.microsoft_face.MicrosoftFace.update_store",
return_value=None,
) as mock_update_store:
yield mock_update_store |
Mock update store. | def store_mock():
"""Mock update store."""
with patch(
"homeassistant.components.microsoft_face.MicrosoftFace.update_store",
return_value=None,
) as mock_update_store:
yield mock_update_store |
Disable polling. | def poll_mock():
"""Disable polling."""
with patch(
"homeassistant.components.microsoft_face_detect.image_processing."
"MicrosoftFaceDetectEntity.should_poll",
new_callable=PropertyMock(return_value=False),
):
yield |
Mock update store. | def store_mock():
"""Mock update store."""
with patch(
"homeassistant.components.microsoft_face.MicrosoftFace.update_store",
return_value=None,
) as mock_update_store:
yield mock_update_store |
Disable polling. | def poll_mock():
"""Disable polling."""
with patch(
"homeassistant.components.microsoft_face_identify.image_processing."
"MicrosoftFaceIdentifyEntity.should_poll",
new_callable=PropertyMock(return_value=False),
):
yield |
Mock an api. | def mock_mikrotik_api():
"""Mock an api."""
with patch("librouteros.connect"):
yield |
Mock an api. | def mock_api_authentication_error():
"""Mock an api."""
with patch(
"librouteros.connect",
side_effect=librouteros.exceptions.TrapError("invalid user name or password"),
):
yield |
Mock an api. | def mock_api_connection_error():
"""Mock an api."""
with patch(
"librouteros.connect", side_effect=librouteros.exceptions.ConnectionClosed
):
yield |
Create device registry devices so the device tracker entities are enabled. | def mock_device_registry_devices(hass: HomeAssistant) -> None:
"""Create device registry devices so the device tracker entities are enabled."""
dev_reg = dr.async_get(hass)
config_entry = MockConfigEntry(domain="something_else")
config_entry.add_to_hass(hass)
for idx, device in enumerate(
(
"00:00:00:00:00:01",
"00:00:00:00:00:02",
"00:00:00:00:00:03",
"00:00:00:00:00:04",
)
):
dev_reg.async_get_or_create(
name=f"Device {idx}",
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, device)},
) |
Mock the Mikrotik command method. | def mock_command(
self, cmd: str, params: dict[str, Any] | None = None, suppress_errors: bool = False
) -> Any:
"""Mock the Mikrotik command method."""
if cmd == mikrotik.const.MIKROTIK_SERVICES[mikrotik.const.IS_WIRELESS]:
return True
if cmd == mikrotik.const.MIKROTIK_SERVICES[mikrotik.const.DHCP]:
return DHCP_DATA
if cmd == mikrotik.const.MIKROTIK_SERVICES[mikrotik.const.WIRELESS]:
return WIRELESS_DATA
return {} |
Mock api. | def mock_api():
"""Mock api."""
with (
patch("librouteros.create_transport"),
patch("librouteros.Api.readResponse") as mock_api,
):
yield mock_api |
Create YouTube entry in Home Assistant. | def java_mock_config_entry() -> MockConfigEntry:
"""Create YouTube entry in Home Assistant."""
return MockConfigEntry(
domain=DOMAIN,
unique_id=None,
entry_id=TEST_CONFIG_ENTRY_ID,
data={
CONF_NAME: DEFAULT_NAME,
CONF_ADDRESS: TEST_ADDRESS,
CONF_TYPE: MinecraftServerType.JAVA_EDITION,
},
version=3,
) |
Create YouTube entry in Home Assistant. | def bedrock_mock_config_entry() -> MockConfigEntry:
"""Create YouTube entry in Home Assistant."""
return MockConfigEntry(
domain=DOMAIN,
unique_id=None,
entry_id=TEST_CONFIG_ENTRY_ID,
data={
CONF_NAME: DEFAULT_NAME,
CONF_ADDRESS: TEST_ADDRESS,
CONF_TYPE: MinecraftServerType.BEDROCK_EDITION,
},
version=3,
) |
Create mock config entry with version 1. | def v1_mock_config_entry() -> MockConfigEntry:
"""Create mock config entry with version 1."""
return MockConfigEntry(
domain=DOMAIN,
unique_id=TEST_UNIQUE_ID,
entry_id=TEST_CONFIG_ENTRY_ID,
data={
CONF_NAME: DEFAULT_NAME,
CONF_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
},
version=1,
) |
Create mock device entry with version 1. | def create_v1_mock_device_entry(hass: HomeAssistant, config_entry_id: str) -> str:
"""Create mock device entry with version 1."""
device_registry = dr.async_get(hass)
device_entry_v1 = device_registry.async_get_or_create(
config_entry_id=config_entry_id,
identifiers={(DOMAIN, TEST_UNIQUE_ID)},
)
device_entry_id = device_entry_v1.id
assert device_entry_v1
assert device_entry_id
return device_entry_id |
Create mock sensor entity entries with version 1. | def create_v1_mock_sensor_entity_entries(
hass: HomeAssistant, config_entry_id: str, device_entry_id: str
) -> list[dict]:
"""Create mock sensor entity entries with version 1."""
sensor_entity_id_key_mapping_list = []
config_entry = hass.config_entries.async_get_entry(config_entry_id)
entity_registry = er.async_get(hass)
for sensor_key in SENSOR_KEYS:
entity_unique_id = f"{TEST_UNIQUE_ID}-{sensor_key['v1']}"
entity_entry_v1 = entity_registry.async_get_or_create(
SENSOR_DOMAIN,
DOMAIN,
unique_id=entity_unique_id,
config_entry=config_entry,
device_id=device_entry_id,
)
assert entity_entry_v1.unique_id == entity_unique_id
sensor_entity_id_key_mapping_list.append(
{"entity_id": entity_entry_v1.entity_id, "key": sensor_key["v2"]}
)
return sensor_entity_id_key_mapping_list |
Create mock binary sensor entity entry with version 1. | def create_v1_mock_binary_sensor_entity_entry(
hass: HomeAssistant, config_entry_id: str, device_entry_id: str
) -> dict:
"""Create mock binary sensor entity entry with version 1."""
config_entry = hass.config_entries.async_get_entry(config_entry_id)
entity_registry = er.async_get(hass)
entity_unique_id = f"{TEST_UNIQUE_ID}-{BINARY_SENSOR_KEYS['v1']}"
entity_entry = entity_registry.async_get_or_create(
BINARY_SENSOR_DOMAIN,
DOMAIN,
unique_id=entity_unique_id,
config_entry=config_entry,
device_id=device_entry_id,
)
assert entity_entry.unique_id == entity_unique_id
return {
"entity_id": entity_entry.entity_id,
"key": BINARY_SENSOR_KEYS["v2"],
} |
Patch Minio client. | def minio_client_fixture():
"""Patch Minio client."""
with patch("homeassistant.components.minio.minio_helper.Minio") as minio_mock:
minio_client_mock = minio_mock.return_value
yield minio_client_mock |
Patch helper function for minio notification stream. | def minio_client_event_fixture():
"""Patch helper function for minio notification stream."""
with patch("homeassistant.components.minio.minio_helper.Minio") as minio_mock:
minio_client_mock = minio_mock.return_value
response_mock = MagicMock()
stream_mock = MagicMock()
stream_mock.__next__.side_effect = [
"",
"",
bytearray(json.dumps(TEST_EVENT), "utf-8"),
]
response_mock.stream.return_value = stream_mock
minio_client_mock._url_open.return_value = response_mock
yield minio_client_mock |
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 |
Return the default mocked config entry. | def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="My MJPEG Camera",
domain=DOMAIN,
data={},
options={
CONF_AUTHENTICATION: HTTP_BASIC_AUTHENTICATION,
CONF_MJPEG_URL: "https://example.com/mjpeg",
CONF_PASSWORD: "supersecret",
CONF_STILL_IMAGE_URL: "http://example.com/still",
CONF_USERNAME: "frenck",
CONF_VERIFY_SSL: True,
},
) |
Mock setting up a config entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Mock setting up a config entry."""
with patch(
"homeassistant.components.mjpeg.async_setup_entry", return_value=True
) as mock_setup:
yield mock_setup |
Mock setting up a config entry. | def mock_reload_entry() -> Generator[AsyncMock, None, None]:
"""Mock setting up a config entry."""
with patch("homeassistant.components.mjpeg.async_reload_entry") as mock_reload:
yield mock_reload |
Fixture to provide a requests mocker. | def mock_mjpeg_requests(requests_mock: Mocker) -> Mocker:
"""Fixture to provide a requests mocker."""
requests_mock.get("https://example.com/mjpeg", text="resp")
requests_mock.get("https://example.com/still", text="resp")
return requests_mock |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Return a encrypted payload given a key and dictionary of data. | def encrypt_payload(secret_key, payload, encode_json=True):
"""Return a encrypted payload given a key and dictionary of data."""
try:
from nacl.encoding import Base64Encoder
from nacl.secret import SecretBox
except (ImportError, OSError):
pytest.skip("libnacl/libsodium is not installed")
return
import json
prepped_key = unhexlify(secret_key)
if encode_json:
payload = json.dumps(payload)
payload = payload.encode("utf-8")
return (
SecretBox(prepped_key).encrypt(payload, encoder=Base64Encoder).decode("utf-8")
) |
Return a encrypted payload given a key and dictionary of data. | def encrypt_payload_legacy(secret_key, payload, encode_json=True):
"""Return a encrypted payload given a key and dictionary of data."""
try:
from nacl.encoding import Base64Encoder
from nacl.secret import SecretBox
except (ImportError, OSError):
pytest.skip("libnacl/libsodium is not installed")
return
import json
keylen = SecretBox.KEY_SIZE
prepped_key = secret_key.encode("utf-8")
prepped_key = prepped_key[:keylen]
prepped_key = prepped_key.ljust(keylen, b"\0")
if encode_json:
payload = json.dumps(payload)
payload = payload.encode("utf-8")
return (
SecretBox(prepped_key).encrypt(payload, encoder=Base64Encoder).decode("utf-8")
) |
Return a decrypted payload given a key and a string of encrypted data. | def decrypt_payload(secret_key, encrypted_data):
"""Return a decrypted payload given a key and a string of encrypted data."""
try:
from nacl.encoding import Base64Encoder
from nacl.secret import SecretBox
except (ImportError, OSError):
pytest.skip("libnacl/libsodium is not installed")
return
import json
prepped_key = unhexlify(secret_key)
decrypted_data = SecretBox(prepped_key).decrypt(
encrypted_data, encoder=Base64Encoder
)
decrypted_data = decrypted_data.decode("utf-8")
return json.loads(decrypted_data) |
Return a decrypted payload given a key and a string of encrypted data. | def decrypt_payload_legacy(secret_key, encrypted_data):
"""Return a decrypted payload given a key and a string of encrypted data."""
try:
from nacl.encoding import Base64Encoder
from nacl.secret import SecretBox
except (ImportError, OSError):
pytest.skip("libnacl/libsodium is not installed")
return
import json
keylen = SecretBox.KEY_SIZE
prepped_key = secret_key.encode("utf-8")
prepped_key = prepped_key[:keylen]
prepped_key = prepped_key.ljust(keylen, b"\0")
decrypted_data = SecretBox(prepped_key).decrypt(
encrypted_data, encoder=Base64Encoder
)
decrypted_data = decrypted_data.decode("utf-8")
return json.loads(decrypted_data) |
Mock pymochad. | def pymochad_mock():
"""Mock pymochad."""
with mock.patch("homeassistant.components.mochad.light.device") as device:
yield device |
Mock light. | def light_mock(hass, brightness):
"""Mock light."""
controller_mock = mock.MagicMock()
dev_dict = {"address": "a1", "name": "fake_light", "brightness_levels": brightness}
return mochad.MochadLight(hass, controller_mock, dev_dict) |
Mock pymochad. | def pymochad_mock():
"""Mock pymochad."""
with (
mock.patch("homeassistant.components.mochad.switch.device"),
mock.patch("homeassistant.components.mochad.switch.MochadException"),
):
yield |
Mock switch. | def switch_mock(hass):
"""Mock switch."""
controller_mock = mock.MagicMock()
dev_dict = {"address": "a1", "name": "fake_switch"}
return mochad.MochadSwitch(hass, controller_mock, dev_dict) |
Set default for check_config_loaded. | def check_config_loaded_fixture():
"""Set default for check_config_loaded."""
return True |
Set default for register_words. | def register_words_fixture():
"""Set default for register_words."""
return [0x00, 0x00] |
Add extra configuration items. | def config_addon_fixture():
"""Add extra configuration items."""
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.