response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
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 module.__all__ is correctly set. | def test_all(module: ModuleType) -> None:
"""Test module.__all__ is correctly set."""
help_test_all(module) |
Test deprecated constants. | def test_deprecated_constants(
caplog: pytest.LogCaptureFixture,
enum: Enum,
constant_prefix: str,
module: ModuleType,
) -> None:
"""Test deprecated constants."""
import_and_test_deprecated_constant_enum(
caplog, module, 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 MockHumidifierEntity(HumidifierEntity):
_attr_mode = "mode1"
@property
def supported_features(self) -> int:
"""Return supported features."""
return 1
entity = MockHumidifierEntity()
assert entity.supported_features_compat is HumidifierEntityFeature(1)
assert "MockHumidifierEntity" in caplog.text
assert "is using deprecated supported features values" in caplog.text
assert "Instead it should use" in caplog.text
assert "HumidifierEntityFeature.MODES" in caplog.text
caplog.clear()
assert entity.supported_features_compat is HumidifierEntityFeature(1)
assert "is using deprecated supported features values" not in caplog.text
assert entity.state_attributes[ATTR_MODE] == "mode1" |
Override async_setup_entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.hunterdouglas_powerview.async_setup_entry",
return_value=True,
) as mock_setup_entry:
yield mock_setup_entry |
Return a mocked Powerview Hub with all data populated. | def mock_hunterdouglas_hub(
device_json: str,
home_json: str,
firmware_json: str,
rooms_json: str,
scenes_json: str,
shades_json: str,
) -> Generator[MagicMock, None, None]:
"""Return a mocked Powerview Hub with all data populated."""
with (
patch(
"homeassistant.components.hunterdouglas_powerview.Hub.request_raw_data",
return_value=load_json_object_fixture(device_json, DOMAIN),
),
patch(
"homeassistant.components.hunterdouglas_powerview.Hub.request_home_data",
return_value=load_json_object_fixture(home_json, DOMAIN),
),
patch(
"homeassistant.components.hunterdouglas_powerview.Hub.request_raw_firmware",
return_value=load_json_object_fixture(firmware_json, DOMAIN),
),
patch(
"homeassistant.components.hunterdouglas_powerview.Rooms.get_resources",
return_value=load_json_value_fixture(rooms_json, DOMAIN),
),
patch(
"homeassistant.components.hunterdouglas_powerview.Scenes.get_resources",
return_value=load_json_value_fixture(scenes_json, DOMAIN),
),
patch(
"homeassistant.components.hunterdouglas_powerview.Shades.get_resources",
return_value=load_json_value_fixture(shades_json, DOMAIN),
),
patch(
"homeassistant.components.hunterdouglas_powerview.cover.BaseShade.refresh",
),
patch(
"homeassistant.components.hunterdouglas_powerview.cover.BaseShade.current_position",
new_callable=PropertyMock,
return_value=ShadePosition(primary=0, secondary=0, tilt=0, velocity=0),
),
):
yield |
Return the request_raw_data fixture for a specific device. | def device_json(api_version: int) -> str:
"""Return the request_raw_data fixture for a specific device."""
if api_version == 1:
return "gen1/userdata.json"
if api_version == 2:
return "gen2/userdata.json"
if api_version == 3:
return "gen3/gateway/primary.json"
# Add more conditions for different api_versions if needed
raise ValueError(f"Unsupported api_version: {api_version}") |
Return the request_home_data fixture for a specific device. | def home_json(api_version: int) -> str:
"""Return the request_home_data fixture for a specific device."""
if api_version == 1:
return "gen1/userdata.json"
if api_version == 2:
return "gen2/userdata.json"
if api_version == 3:
return "gen3/home/home.json"
# Add more conditions for different api_versions if needed
raise ValueError(f"Unsupported api_version: {api_version}") |
Return the request_raw_firmware fixture for a specific device. | def firmware_json(api_version: int) -> str:
"""Return the request_raw_firmware fixture for a specific device."""
if api_version == 1:
return "gen1/fwversion.json"
if api_version == 2:
return "gen2/fwversion.json"
if api_version == 3:
return "gen3/gateway/info.json"
# Add more conditions for different api_versions if needed
raise ValueError(f"Unsupported api_version: {api_version}") |
Return the get_resources fixture for a specific device. | def rooms_json(api_version: int) -> str:
"""Return the get_resources fixture for a specific device."""
if api_version == 1:
return "gen2/rooms.json"
if api_version == 2:
return "gen2/rooms.json"
if api_version == 3:
return "gen3/home/rooms.json"
# Add more conditions for different api_versions if needed
raise ValueError(f"Unsupported api_version: {api_version}") |
Return the get_resources fixture for a specific device. | def scenes_json(api_version: int) -> str:
"""Return the get_resources fixture for a specific device."""
if api_version == 1:
return "gen2/scenes.json"
if api_version == 2:
return "gen2/scenes.json"
if api_version == 3:
return "gen3/home/scenes.json"
# Add more conditions for different api_versions if needed
raise ValueError(f"Unsupported api_version: {api_version}") |
Return the get_resources fixture for a specific device. | def shades_json(api_version: int) -> str:
"""Return the get_resources fixture for a specific device."""
if api_version == 1:
return "gen2/shades.json"
if api_version == 2:
return "gen2/shades.json"
if api_version == 3:
return "gen3/home/shades.json"
# Add more conditions for different api_versions if needed
raise ValueError(f"Unsupported api_version: {api_version}") |
Load Fixture data. | def load_jwt_fixture():
"""Load Fixture data."""
return load_fixture("jwt", DOMAIN) |
Fixture to set the oauth token expiration time. | def mock_expires_at() -> float:
"""Fixture to set the oauth token expiration time."""
return time.time() + 3600 |
Return the default mocked config entry. | def mock_config_entry(jwt, expires_at: int) -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
version=1,
domain=DOMAIN,
title="Husqvarna Automower of Erika Mustermann",
data={
"auth_implementation": DOMAIN,
"token": {
"access_token": jwt,
"scope": "iam:read amc:api",
"expires_in": 86399,
"refresh_token": "3012bc9f-7a65-4240-b817-9154ffdcc30f",
"provider": "husqvarna",
"user_id": USER_ID,
"token_type": "Bearer",
"expires_at": expires_at,
},
},
unique_id=USER_ID,
entry_id="automower_test",
) |
Mock a Husqvarna Automower client. | def mock_automower_client() -> Generator[AsyncMock, None, None]:
"""Mock a Husqvarna Automower client."""
with patch(
"homeassistant.components.husqvarna_automower.AutomowerSession",
autospec=True,
) as mock_client:
client = mock_client.return_value
client.get_status.return_value = mower_list_to_dictionary_dataclass(
load_json_value_fixture("mower.json", DOMAIN)
)
async def websocket_connect() -> ClientWebSocketResponse:
"""Mock listen."""
return ClientWebSocketResponse
client.auth = AsyncMock(side_effect=websocket_connect)
yield client |
Override async_setup_entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.hydrawise.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry |
Mock LegacyHydrawiseAsync. | def mock_legacy_pydrawise(
user: User,
controller: Controller,
zones: list[Zone],
) -> Generator[AsyncMock, None, None]:
"""Mock LegacyHydrawiseAsync."""
with patch(
"pydrawise.legacy.LegacyHydrawiseAsync", autospec=True
) as mock_pydrawise:
user.controllers = [controller]
controller.zones = zones
mock_pydrawise.return_value.get_user.return_value = user
yield mock_pydrawise.return_value |
Mock Hydrawise. | def mock_pydrawise(
mock_auth: AsyncMock,
user: User,
controller: Controller,
zones: list[Zone],
) -> Generator[AsyncMock, None, None]:
"""Mock Hydrawise."""
with patch("pydrawise.client.Hydrawise", autospec=True) as mock_pydrawise:
user.controllers = [controller]
controller.zones = zones
mock_pydrawise.return_value.get_user.return_value = user
yield mock_pydrawise.return_value |
Mock pydrawise Auth. | def mock_auth() -> Generator[AsyncMock, None, None]:
"""Mock pydrawise Auth."""
with patch("pydrawise.auth.Auth", autospec=True) as mock_auth:
yield mock_auth.return_value |
Hydrawise User fixture. | def user() -> User:
"""Hydrawise User fixture."""
return User(customer_id=12345, email="[email protected]") |
Hydrawise Controller fixture. | def controller() -> Controller:
"""Hydrawise Controller fixture."""
return Controller(
id=52496,
name="Home Controller",
hardware=ControllerHardware(
serial_number="0310b36090",
),
last_contact_time=datetime.fromtimestamp(1693292420),
online=True,
) |
Hydrawise zone fixtures. | def zones() -> list[Zone]:
"""Hydrawise zone fixtures."""
return [
Zone(
name="Zone One",
number=1,
id=5965394,
scheduled_runs=ScheduledZoneRuns(
summary="",
current_run=None,
next_run=ScheduledZoneRun(
start_time=dt_util.now() + timedelta(seconds=330597),
end_time=dt_util.now()
+ timedelta(seconds=330597)
+ timedelta(seconds=1800),
normal_duration=timedelta(seconds=1800),
duration=timedelta(seconds=1800),
),
),
),
Zone(
name="Zone Two",
number=2,
id=5965395,
scheduled_runs=ScheduledZoneRuns(
current_run=ScheduledZoneRun(
remaining_time=timedelta(seconds=1788),
),
),
),
] |
Mock ConfigEntry. | def mock_config_entry_legacy() -> MockConfigEntry:
"""Mock ConfigEntry."""
return MockConfigEntry(
title="Hydrawise",
domain=DOMAIN,
data={
CONF_API_KEY: "abc123",
},
unique_id="hydrawise-customerid",
version=1,
) |
Mock ConfigEntry. | def mock_config_entry() -> MockConfigEntry:
"""Mock ConfigEntry."""
return MockConfigEntry(
title="Hydrawise",
domain=DOMAIN,
data={
CONF_USERNAME: "[email protected]",
CONF_PASSWORD: "__password__",
},
unique_id="hydrawise-customerid",
version=1,
minor_version=2,
) |
Test that devices are added to the device registry. | def test_zones_in_device_registry(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_added_config_entry: ConfigEntry,
mock_pydrawise: Mock,
) -> None:
"""Test that devices are added to the device registry."""
device1 = device_registry.async_get_device(identifiers={(DOMAIN, "5965394")})
assert device1 is not None
assert device1.name == "Zone One"
assert device1.manufacturer == "Hydrawise"
device2 = device_registry.async_get_device(identifiers={(DOMAIN, "5965395")})
assert device2 is not None
assert device2.name == "Zone Two"
assert device2.manufacturer == "Hydrawise" |
Test that devices are added to the device registry. | def test_controller_in_device_registry(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_added_config_entry: ConfigEntry,
mock_pydrawise: Mock,
) -> None:
"""Test that devices are added to the device registry."""
device = device_registry.async_get_device(identifiers={(DOMAIN, "52496")})
assert device is not None
assert device.name == "Home Controller"
assert device.manufacturer == "Hydrawise" |
Create a mock Hyperion client. | def create_mock_client() -> Mock:
"""Create a mock Hyperion client."""
mock_client = AsyncContextManagerMock()
# pylint: disable=attribute-defined-outside-init
mock_client.async_client_connect = AsyncMock(return_value=True)
mock_client.async_client_disconnect = AsyncMock(return_value=True)
mock_client.async_is_auth_required = AsyncMock(
return_value=TEST_AUTH_NOT_REQUIRED_RESP
)
mock_client.async_login = AsyncMock(
return_value={"command": "authorize-login", "success": True, "tan": 0}
)
mock_client.async_sysinfo_id = AsyncMock(return_value=TEST_SYSINFO_ID)
mock_client.async_sysinfo_version = AsyncMock(return_value=TEST_SYSINFO_VERSION)
mock_client.async_client_switch_instance = AsyncMock(return_value=True)
mock_client.async_client_login = AsyncMock(return_value=True)
mock_client.async_get_serverinfo = AsyncMock(
return_value={
"command": "serverinfo",
"success": True,
"tan": 0,
"info": {"fake": "data"},
}
)
mock_client.priorities = []
mock_client.adjustment = None
mock_client.effects = None
mock_client.instances = [
{"friendly_name": "Test instance 1", "instance": 0, "running": True}
]
mock_client.remote_url = f"http://{TEST_HOST}:{TEST_PORT_UI}"
return mock_client |
Add a test config entry. | def add_test_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_HOST: TEST_HOST,
CONF_PORT: TEST_PORT,
},
title=f"Hyperion {TEST_SYSINFO_ID}",
unique_id=TEST_SYSINFO_ID,
options=options or TEST_CONFIG_ENTRY_OPTIONS,
)
config_entry.add_to_hass(hass)
return config_entry |
Call Hyperion entity callbacks that were registered with the client. | def call_registered_callback(
client: AsyncMock, key: str, *args: Any, **kwargs: Any
) -> None:
"""Call Hyperion entity callbacks that were registered with the client."""
for call in client.add_callbacks.call_args_list:
if key in call[0][0]:
call[0][0][key](*args, **kwargs) |
Register a test entity. | def register_test_entity(
hass: HomeAssistant, domain: str, type_name: str, entity_id: str
) -> None:
"""Register a test entity."""
unique_id = get_hyperion_unique_id(TEST_SYSINFO_ID, TEST_INSTANCE, type_name)
entity_id = entity_id.split(".")[1]
entity_registry = er.async_get(hass)
entity_registry.async_get_or_create(
domain,
DOMAIN,
unique_id,
suggested_object_id=entity_id,
disabled_by=None,
) |
Set up IAlarm API fixture. | def ialarm_api_fixture():
"""Set up IAlarm API fixture."""
with patch("homeassistant.components.ialarm.IAlarm") as mock_ialarm_api:
yield mock_ialarm_api |
Return a fake config entry. | def mock_config_fixture():
"""Return a fake config entry."""
return MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: "192.168.10.20", CONF_PORT: 18034},
entry_id=str(uuid4()),
) |
Return value-returning async mock. | def async_returns(x):
"""Return value-returning async mock."""
return AsyncMock(return_value=x) |
Return exception-raising async mock. | def async_raises(x):
"""Return exception-raising async mock."""
return AsyncMock(side_effect=x) |
Create client fixture. | def client_fixture():
"""Create client fixture."""
return AqualinkClient(username=MOCK_USERNAME, password=MOCK_PASSWORD) |
Create aqualink system. | def get_aqualink_system(aqualink, cls=None, data=None):
"""Create aqualink system."""
if cls is None:
cls = AqualinkSystem
if data is None:
data = {}
num = random.randint(0, 99999)
data["serial_number"] = f"SN{num:05}"
return cls(aqualink=aqualink, data=data) |
Create aqualink device. | def get_aqualink_device(system, name, cls=None, data=None):
"""Create aqualink device."""
if cls is None:
cls = AqualinkDevice
# AqualinkDevice doesn't implement some of the properties since it's left to
# sub-classes for them to do. Provide a basic implementation here for the
# benefits of the test suite.
attrs = {
"name": name,
"manufacturer": "Jandy",
"model": "Device",
"label": name.upper(),
}
for k, v in attrs.items():
patcher = patch.object(cls, k, new_callable=PropertyMock)
mock = patcher.start()
mock.return_value = v
if data is None:
data = {}
data["name"] = name
return cls(system=system, data=data) |
Create hass config fixture. | def config_data_fixture():
"""Create hass config fixture."""
return MOCK_DATA |
Create hass config fixture. | def config_fixture():
"""Create hass config fixture."""
return {DOMAIN: MOCK_DATA} |
Create a mock config entry. | def config_entry_fixture():
"""Create a mock config entry."""
return MockConfigEntry(
domain=DOMAIN,
data=MOCK_DATA,
) |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Replace attributes of a BluetoothServiceInfoBleak. | def bluetooth_service_info_replace(
info: BluetoothServiceInfo, **kwargs: Any
) -> BluetoothServiceInfo:
"""Replace attributes of a BluetoothServiceInfoBleak."""
return BluetoothServiceInfo(
address=kwargs.get("address", info.address),
name=kwargs.get("name", info.name),
rssi=kwargs.get("rssi", info.rssi),
manufacturer_data=kwargs.get("manufacturer_data", info.manufacturer_data),
service_data=kwargs.get("service_data", info.service_data),
service_uuids=kwargs.get("service_uuids", info.service_uuids),
source=kwargs.get("source", info.source),
) |
Mock component setup. | def icloud_not_create_dir():
"""Mock component setup."""
with patch(
"homeassistant.components.icloud.config_flow.os.path.exists", return_value=True
):
yield |
Mock component setup. | def icloud_bypass_setup_fixture():
"""Mock component setup."""
with patch("homeassistant.components.icloud.async_setup_entry", return_value=True):
yield |
Mock a successful service. | def mock_controller_service():
"""Mock a successful service."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = False
service_mock.return_value.requires_2sa = True
service_mock.return_value.trusted_devices = TRUSTED_DEVICES
service_mock.return_value.send_verification_code = Mock(return_value=True)
service_mock.return_value.validate_verification_code = Mock(return_value=True)
yield service_mock |
Mock a successful 2fa service. | def mock_controller_2fa_service():
"""Mock a successful 2fa service."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = True
service_mock.return_value.requires_2sa = True
service_mock.return_value.validate_2fa_code = Mock(return_value=True)
service_mock.return_value.is_trusted_session = False
yield service_mock |
Mock a successful service while already authenticate. | def mock_controller_service_authenticated():
"""Mock a successful service while already authenticate."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = False
service_mock.return_value.requires_2sa = False
service_mock.return_value.is_trusted_session = True
service_mock.return_value.trusted_devices = TRUSTED_DEVICES
service_mock.return_value.send_verification_code = Mock(return_value=True)
service_mock.return_value.validate_2fa_code = Mock(return_value=True)
service_mock.return_value.validate_verification_code = Mock(return_value=True)
yield service_mock |
Mock a successful service while already authenticate, but without device. | def mock_controller_service_authenticated_no_device():
"""Mock a successful service while already authenticate, but without device."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = False
service_mock.return_value.requires_2sa = False
service_mock.return_value.trusted_devices = TRUSTED_DEVICES
service_mock.return_value.send_verification_code = Mock(return_value=True)
service_mock.return_value.validate_verification_code = Mock(return_value=True)
service_mock.return_value.devices = {}
yield service_mock |
Mock a successful service while already authenticated, but the session is not trusted. | def mock_controller_service_authenticated_not_trusted():
"""Mock a successful service while already authenticated, but the session is not trusted."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = False
service_mock.return_value.requires_2sa = False
service_mock.return_value.is_trusted_session = False
service_mock.return_value.trusted_devices = TRUSTED_DEVICES
service_mock.return_value.send_verification_code = Mock(return_value=True)
service_mock.return_value.validate_2fa_code = Mock(return_value=True)
service_mock.return_value.validate_verification_code = Mock(return_value=True)
yield service_mock |
Mock a failed service during sending verification code step. | def mock_controller_service_send_verification_code_failed():
"""Mock a failed service during sending verification code step."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = False
service_mock.return_value.requires_2sa = True
service_mock.return_value.trusted_devices = TRUSTED_DEVICES
service_mock.return_value.send_verification_code = Mock(return_value=False)
yield service_mock |
Mock a failed service during validation of 2FA verification code step. | def mock_controller_service_validate_2fa_code_failed():
"""Mock a failed service during validation of 2FA verification code step."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = True
service_mock.return_value.validate_2fa_code = Mock(return_value=False)
yield service_mock |
Mock a failed service during validation of verification code step. | def mock_controller_service_validate_verification_code_failed():
"""Mock a failed service during validation of verification code step."""
with patch(
"homeassistant.components.icloud.config_flow.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = False
service_mock.return_value.requires_2sa = True
service_mock.return_value.trusted_devices = TRUSTED_DEVICES
service_mock.return_value.send_verification_code = Mock(return_value=True)
service_mock.return_value.validate_verification_code = Mock(return_value=False)
yield service_mock |
Mock a successful 2fa service. | def mock_controller_2fa_service():
"""Mock a successful 2fa service."""
with patch(
"homeassistant.components.icloud.account.PyiCloudService"
) as service_mock:
service_mock.return_value.requires_2fa = True
service_mock.return_value.requires_2sa = True
service_mock.return_value.validate_2fa_code = Mock(return_value=True)
service_mock.return_value.is_trusted_session = False
yield service_mock |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth."""
with mock.patch(
"homeassistant.components.idasen_desk.bluetooth.async_ble_device_from_address"
):
yield MagicMock() |
Set up idasen desk API fixture. | def mock_desk_api():
"""Set up idasen desk API fixture."""
with mock.patch("homeassistant.components.idasen_desk.Desk") as desk_patched:
mock_desk = MagicMock()
def mock_init(
update_callback: Callable[[int | None], None] | None,
monitor_height: bool = True,
):
mock_desk.trigger_update_callback = update_callback
return mock_desk
desk_patched.side_effect = mock_init
async def mock_connect(ble_device):
mock_desk.is_connected = True
mock_desk.trigger_update_callback(None)
async def mock_disconnect():
mock_desk.is_connected = False
mock_desk.trigger_update_callback(None)
async def mock_move_to(height: float):
mock_desk.height_percent = height
mock_desk.trigger_update_callback(height)
async def mock_move_up():
await mock_move_to(100)
async def mock_move_down():
await mock_move_to(0)
mock_desk.connect = AsyncMock(side_effect=mock_connect)
mock_desk.disconnect = AsyncMock(side_effect=mock_disconnect)
mock_desk.move_to = AsyncMock(side_effect=mock_move_to)
mock_desk.move_up = AsyncMock(side_effect=mock_move_up)
mock_desk.move_down = AsyncMock(side_effect=mock_move_down)
mock_desk.stop = AsyncMock()
mock_desk.height = 1
mock_desk.height_percent = 60
mock_desk.is_moving = False
mock_desk.address = "AA:BB:CC:DD:EE:FF"
yield mock_desk |
Construct a mock feed entry for testing purposes. | def _generate_mock_feed_entry(
external_id,
title,
distance_to_home,
coordinates,
region=None,
attribution=None,
published=None,
magnitude=None,
image_url=None,
):
"""Construct a mock feed entry for testing purposes."""
feed_entry = MagicMock()
feed_entry.external_id = external_id
feed_entry.title = title
feed_entry.distance_to_home = distance_to_home
feed_entry.coordinates = coordinates
feed_entry.region = region
feed_entry.attribution = attribution
feed_entry.published = published
feed_entry.magnitude = magnitude
feed_entry.image_url = image_url
return feed_entry |
Mock config flow. | def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]:
"""Mock config flow."""
class MockFlow(ConfigFlow):
"""Test flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
with mock_config_flow(TEST_DOMAIN, MockFlow):
yield |
Force process of all cameras or given entity. | def scan(hass, entity_id=ENTITY_MATCH_ALL):
"""Force process of all cameras or given entity."""
hass.add_job(async_scan, hass, entity_id) |
Force process of all cameras or given entity. | def async_scan(hass, entity_id=ENTITY_MATCH_ALL):
"""Force process of all cameras or given entity."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_SCAN, data)) |
Return aiohttp_unused_port and allow opening sockets. | def aiohttp_unused_port_factory(event_loop, unused_tcp_port_factory, socket_enabled):
"""Return aiohttp_unused_port and allow opening sockets."""
return unused_tcp_port_factory |
Return camera url. | def get_url(hass):
"""Return camera url."""
state = hass.states.get("camera.demo_camera")
return f"{hass.config.internal_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}" |
Override async_setup_entry. | def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.imap.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry |
Fixture to set the imap capabilities. | def imap_has_capability() -> bool:
"""Fixture to set the imap capabilities."""
return True |
Fixture to set the imap state after login. | def imap_login_state() -> str:
"""Fixture to set the imap state after login."""
return AUTH |
Fixture to set the imap capabilities. | def imap_select_state() -> str:
"""Fixture to set the imap capabilities."""
return SELECTED |
Fixture to set the imap search response. | def imap_search() -> tuple[str, list[bytes]]:
"""Fixture to set the imap search response."""
return EMPTY_SEARCH_RESPONSE |
Fixture to set the imap fetch response. | def imap_fetch() -> tuple[str, list[bytes | bytearray]]:
"""Fixture to set the imap fetch response."""
return TEST_FETCH_RESPONSE_TEXT_PLAIN |
Fixture to set the imap pending idle feature. | def imap_pending_idle() -> bool:
"""Fixture to set the imap pending idle feature."""
return True |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Mock the event bus listener and the batch timeout for tests. | def mock_batch_timeout(hass, monkeypatch):
"""Mock the event bus listener and the batch timeout for tests."""
monkeypatch.setattr(
f"{INFLUX_PATH}.InfluxThread.batch_timeout",
Mock(return_value=0),
) |
Patch the InfluxDBClient object with mock for version under test. | def mock_client_fixture(request):
"""Patch the InfluxDBClient object with mock for version under test."""
if request.param == influxdb.API_VERSION_2:
client_target = f"{INFLUX_CLIENT_PATH}V2"
else:
client_target = INFLUX_CLIENT_PATH
with patch(client_target) as client:
yield client |
Get version specific lambda to make write API call mock. | def get_mock_call_fixture(request):
"""Get version specific lambda to make write API call mock."""
def v2_call(body, precision):
data = {"bucket": DEFAULT_BUCKET, "record": body}
if precision is not None:
data["write_precision"] = precision
return call(**data)
if request.param == influxdb.API_VERSION_2:
return lambda body, precision=None: v2_call(body, precision)
# pylint: disable-next=unnecessary-lambda
return lambda body, precision=None: call(body, time_precision=precision) |
Return the write api mock for the V1 client. | def _get_write_api_mock_v1(mock_influx_client):
"""Return the write api mock for the V1 client."""
return mock_influx_client.return_value.write_points |
Return the write api mock for the V2 client. | def _get_write_api_mock_v2(mock_influx_client):
"""Return the write api mock for the V2 client."""
return mock_influx_client.return_value.write_api.return_value.write |
Patch the InfluxDBClient object with mock for version under test. | def mock_client_fixture(request):
"""Patch the InfluxDBClient object with mock for version under test."""
if request.param == API_VERSION_2:
client_target = f"{INFLUXDB_CLIENT_PATH}V2"
else:
client_target = INFLUXDB_CLIENT_PATH
with patch(client_target) as client:
yield client |
Mock close method of clients at module scope. | def mock_client_close():
"""Mock close method of clients at module scope."""
with (
patch(f"{INFLUXDB_CLIENT_PATH}.close") as close_v1,
patch(f"{INFLUXDB_CLIENT_PATH}V2.close") as close_v2,
):
yield (close_v1, close_v2) |
Create a mock V1 resultset. | def _make_v1_resultset(*args):
"""Create a mock V1 resultset."""
for arg in args:
yield {"value": arg} |
Create a mock V1 'show databases' resultset. | def _make_v1_databases_resultset():
"""Create a mock V1 'show databases' resultset."""
for name in [DEFAULT_DATABASE, "db2"]:
yield {"name": name} |
Create a mock V2 resultset. | def _make_v2_resultset(*args):
"""Create a mock V2 resultset."""
tables = []
for arg in args:
values = {"_value": arg}
record = Record(values)
tables.append(Table([record]))
return tables |
Create a mock V2 'buckets()' resultset. | def _make_v2_buckets_resultset():
"""Create a mock V2 'buckets()' resultset."""
records = [Record({"name": name}) for name in [DEFAULT_BUCKET, "bucket2"]]
return [Table(records)] |
Set return value or side effect for the V1 client. | def _set_query_mock_v1(
mock_influx_client, return_value=None, query_exception=None, side_effect=None
):
"""Set return value or side effect for the V1 client."""
query_api = mock_influx_client.return_value.query
if side_effect:
query_api.side_effect = side_effect
else:
if return_value is None:
return_value = []
def get_return_value(query, **kwargs):
"""Return mock for test query, return value otherwise."""
if query == TEST_QUERY_V1:
points = _make_v1_databases_resultset()
else:
if query_exception:
raise query_exception
points = return_value
query_output = MagicMock()
query_output.get_points.return_value = points
return query_output
query_api.side_effect = get_return_value
return query_api |
Set return value or side effect for the V2 client. | def _set_query_mock_v2(
mock_influx_client, return_value=None, query_exception=None, side_effect=None
):
"""Set return value or side effect for the V2 client."""
query_api = mock_influx_client.return_value.query_api.return_value.query
if side_effect:
query_api.side_effect = side_effect
else:
if return_value is None:
return_value = []
def get_return_value(query):
"""Return buckets list for test query, return value otherwise."""
if query == TEST_QUERY_V2:
return _make_v2_buckets_resultset()
if query_exception:
raise query_exception
return return_value
query_api.side_effect = get_return_value
return query_api |
Auto mock bluetooth. | def mock_bluetooth(enable_bluetooth):
"""Auto mock bluetooth.""" |
Storage setup. | def storage_setup(hass, hass_storage):
"""Storage setup."""
async def _storage(items=None, config=None):
if items is None:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {"items": [{"id": "from_storage", "name": "from storage"}]},
}
else:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {"items": items},
}
if config is None:
config = {DOMAIN: {}}
return await async_setup_component(hass, DOMAIN, config)
return _storage |
Storage setup. | def storage_setup(hass, hass_storage):
"""Storage setup."""
async def _storage(items=None, config=None):
if items is None:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {"items": [{"id": "from_storage", "name": "from storage"}]},
}
else:
hass_storage[DOMAIN] = items
if config is None:
config = {DOMAIN: {}}
return await async_setup_component(hass, DOMAIN, config)
return _storage |
Storage setup. | def storage_setup(hass, hass_storage):
"""Storage setup."""
async def _storage(items=None, config=None):
if items is None:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {
"items": [
{
CONF_ID: "from_storage",
CONF_NAME: "datetime from storage",
CONF_INITIAL: INITIAL_DATETIME,
CONF_HAS_DATE: True,
CONF_HAS_TIME: True,
}
]
},
}
else:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {"items": items},
}
if config is None:
config = {DOMAIN: {}}
return await async_setup_component(hass, DOMAIN, config)
return _storage |
Test config. | def test_invalid_configs(config) -> None:
"""Test config."""
with pytest.raises(vol.Invalid):
CONFIG_SCHEMA({DOMAIN: config}) |
Storage setup. | def storage_setup(hass, hass_storage):
"""Storage setup."""
async def _storage(items=None, config=None):
if items is None:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {
"items": [
{
"id": "from_storage",
"initial": 10,
"name": "from storage",
"max": 100,
"min": 0,
"step": 1,
"mode": "slider",
}
]
},
}
else:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {"items": items},
}
if config is None:
config = {DOMAIN: {}}
return await async_setup_component(hass, DOMAIN, config)
return _storage |
Storage setup. | def storage_setup(hass, hass_storage):
"""Storage setup."""
async def _storage(items=None, config=None, minor_version=STORAGE_VERSION_MINOR):
if items is None:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": STORAGE_VERSION,
"minor_version": minor_version,
"data": {
"items": [
{
"id": "from_storage",
"name": "from storage",
"options": ["storage option 1", "storage option 2"],
}
]
},
}
else:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"minor_version": minor_version,
"data": {"items": items},
}
if config is None:
config = {DOMAIN: {}}
return await async_setup_component(hass, DOMAIN, config)
return _storage |
Storage setup. | def storage_setup(hass, hass_storage):
"""Storage setup."""
async def _storage(items=None, config=None):
if items is None:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {
"items": [
{
"id": "from_storage",
"name": "from storage",
"initial": "loaded from storage",
ATTR_MAX: TEST_VAL_MAX,
ATTR_MIN: TEST_VAL_MIN,
ATTR_MODE: MODE_TEXT,
}
]
},
}
else:
hass_storage[DOMAIN] = {
"key": DOMAIN,
"version": 1,
"data": {"items": items},
}
if config is None:
config = {DOMAIN: {}}
return await async_setup_component(hass, DOMAIN, config)
return _storage |
Load the controller state fixture data. | def aldb_data_fixture():
"""Load the controller state fixture data."""
return json.loads(load_fixture("insteon/aldb_data.json")) |
Compare a record in the ALDB to the dictionary record. | def _compare_records(aldb_rec, dict_rec):
"""Compare a record in the ALDB to the dictionary record."""
assert aldb_rec.is_in_use == dict_rec["in_use"]
assert aldb_rec.is_controller == (dict_rec["is_controller"])
assert not aldb_rec.is_high_water_mark
assert aldb_rec.group == dict_rec["group"]
assert aldb_rec.target == Address(dict_rec["target"])
assert aldb_rec.data1 == dict_rec["data1"]
assert aldb_rec.data2 == dict_rec["data2"]
assert aldb_rec.data3 == dict_rec["data3"] |
Generate an ALDB record as a dictionary. | def _aldb_dict(mem_addr):
"""Generate an ALDB record as a dictionary."""
return {
"mem_addr": mem_addr,
"in_use": True,
"is_controller": True,
"highwater": False,
"group": 100,
"target": "111111",
"data1": 101,
"data2": 102,
"data3": 103,
"dirty": True,
} |
Load the controller state fixture data. | def kpl_properties_data_fixture():
"""Load the controller state fixture data."""
return json.loads(load_fixture("insteon/kpl_properties.json")) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.