response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Load the controller state fixture data.
def iolinc_properties_data_fixture(): """Load the controller state fixture data.""" return json.loads(load_fixture("insteon/iolinc_properties.json"))
Load the controller state fixture data.
def aldb_data_fixture(): """Load the controller state fixture data.""" return json.loads(load_fixture("insteon/scene_data.json"))
Fixture to remove insteon_devices.json at the end of the test.
def remove_insteon_devices_json(hass): """Fixture to remove insteon_devices.json at the end of the test.""" yield file = os.path.join(hass.config.config_dir, "insteon_devices.json") if os.path.exists(file): os.remove(file)
Convert a scene object to a dictionary.
def _scene_to_array(scene): """Convert a scene object to a dictionary.""" scene_list = [] for device, links in scene["devices"].items(): for link in links: link_dict = {} link_dict["address"] = device.id link_dict["data1"] = link.data1 link_dict["data2"] = link.data2 link_dict["data3"] = link.data3 scene_list.append(link_dict) return scene_list
Only setup the lock and required base platforms to speed up tests.
def patch_usb_list(): """Only setup the lock and required base platforms to speed up tests.""" with patch( PATCH_USB_LIST, mock_usb_list, ): yield
Only setup the lock and required base platforms to speed up tests.
def lock_platform_only(): """Only setup the lock and required base platforms to speed up tests.""" with patch( "homeassistant.components.insteon.INSTEON_PLATFORMS", (Platform.LOCK,), ): yield
Patch the Insteon setup process and devices.
def patch_setup_and_devices(): """Patch the Insteon setup process and devices.""" with ( patch.object(insteon, "async_connect", new=mock_connection), patch.object(insteon, "async_close"), patch.object(insteon, "devices", devices), patch.object(insteon_utils, "devices", devices), patch.object( insteon_entity, "devices", devices, ), ): yield
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 setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.intellifire.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Mock fireplace finder.
def mock_fireplace_finder_none() -> Generator[None, MagicMock, None]: """Mock fireplace finder.""" mock_found_fireplaces = Mock() mock_found_fireplaces.ips = [] with patch( "homeassistant.components.intellifire.config_flow.AsyncUDPFireplaceFinder.search_fireplace" ): yield mock_found_fireplaces
Mock fireplace finder.
def mock_fireplace_finder_single() -> Generator[None, MagicMock, None]: """Mock fireplace finder.""" mock_found_fireplaces = Mock() mock_found_fireplaces.ips = ["192.168.1.69"] with patch( "homeassistant.components.intellifire.config_flow.AsyncUDPFireplaceFinder.search_fireplace" ): yield mock_found_fireplaces
Return a mocked IntelliFire client.
def mock_intellifire_config_flow() -> Generator[None, MagicMock, None]: """Return a mocked IntelliFire client.""" data_mock = Mock() data_mock.serial = "12345" with patch( "homeassistant.components.intellifire.config_flow.IntellifireAPILocal", autospec=True, ) as intellifire_mock: intellifire = intellifire_mock.return_value intellifire.data = data_mock yield intellifire
Return a fake a ConnectionError for iftapi.net.
def mock_api_connection_error() -> ConnectionError: """Return a fake a ConnectionError for iftapi.net.""" ret = ConnectionError() ret.args = [ConnectionKey("iftapi.net", 443, False, None, None, None, None)] return ret
Mock load_json.
def mock_load_json(): """Mock load_json.""" with patch("homeassistant.components.ios.load_json_object", return_value={}): yield
Mock dependencies loaded.
def mock_dependencies(hass): """Mock dependencies loaded.""" mock_component(hass, "zeroconf") mock_component(hass, "device_tracker")
Mock config entry added to HA.
def entry(hass): """Mock config entry added to HA.""" entry = MockConfigEntry(domain=DOMAIN, data={"host": "1.2.3.4"}) entry.add_to_hass(hass) return entry
Mock iotawatt.
def mock_iotawatt(entry): """Mock iotawatt.""" with patch("homeassistant.components.iotawatt.coordinator.Iotawatt") as mock: instance = mock.return_value instance.connect = AsyncMock(return_value=True) instance.update = AsyncMock() instance.getSensors.return_value = {"sensors": {}} yield instance
Define a config entry fixture.
def config_entry(hass): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, data={ CONF_NAME: "Home", CONF_LATITUDE: 0, CONF_LONGITUDE: 0, }, ) entry.add_to_hass(hass) return entry
Patch ipma setup entry.
def ipma_setup_fixture(request): """Patch ipma setup entry.""" with patch("homeassistant.components.ipma.async_setup_entry", return_value=True): yield
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="IPP Printer", domain=DOMAIN, data={ CONF_HOST: "192.168.1.31", CONF_PORT: 631, CONF_SSL: False, CONF_VERIFY_SSL: True, CONF_BASE_PATH: "/ipp/print", CONF_UUID: "cfe92100-67c4-11d4-a45f-f8d027761251", }, unique_id="cfe92100-67c4-11d4-a45f-f8d027761251", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.ipp.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return a mocked IPP client.
def mock_ipp_config_flow( mock_printer: Printer, ) -> Generator[None, MagicMock, None]: """Return a mocked IPP client.""" with patch( "homeassistant.components.ipp.config_flow.IPP", autospec=True ) as ipp_mock: client = ipp_mock.return_value client.printer.return_value = mock_printer yield client
Return a mocked IPP client.
def mock_ipp( request: pytest.FixtureRequest, mock_printer: Printer ) -> Generator[None, MagicMock, None]: """Return a mocked IPP client.""" with patch( "homeassistant.components.ipp.coordinator.IPP", autospec=True ) as ipp_mock: client = ipp_mock.return_value client.printer.return_value = mock_printer yield client
Define a config entry fixture.
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=config[CONF_ZIP_CODE], data=config, entry_id="690ac4b7e99855fc5ee7b987a758d5cb", ) entry.add_to_hass(hass) return entry
Define a config entry data fixture.
def config_fixture(hass): """Define a config entry data fixture.""" return { CONF_ZIP_CODE: "12345", }
Define allergy forecast data.
def data_allergy_forecast_fixture(): """Define allergy forecast data.""" return json.loads(load_fixture("allergy_forecast_data.json", "iqvia"))
Define allergy index data.
def data_allergy_index_fixture(): """Define allergy index data.""" return json.loads(load_fixture("allergy_index_data.json", "iqvia"))
Define allergy outlook data.
def data_allergy_outlook_fixture(): """Define allergy outlook data.""" return json.loads(load_fixture("allergy_outlook_data.json", "iqvia"))
Define asthma forecast data.
def data_asthma_forecast_fixture(): """Define asthma forecast data.""" return json.loads(load_fixture("asthma_forecast_data.json", "iqvia"))
Define asthma index data.
def data_asthma_index_fixture(): """Define asthma index data.""" return json.loads(load_fixture("asthma_index_data.json", "iqvia"))
Define disease forecast data.
def data_disease_forecast_fixture(): """Define disease forecast data.""" return json.loads(load_fixture("disease_forecast_data.json", "iqvia"))
Define disease index data.
def data_disease_index_fixture(): """Define disease index data.""" return json.loads(load_fixture("disease_index_data.json", "iqvia"))
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.islamic_prayer_times.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Set timezone to UTC.
def set_utc(hass: HomeAssistant) -> None: """Set timezone to UTC.""" hass.config.set_time_zone("UTC")
Set timezone to UTC.
def set_utc(hass: HomeAssistant) -> None: """Set timezone to UTC.""" hass.config.set_time_zone("UTC")
Iterate schema to find a key.
def _get_schema_default(schema, key_name): """Iterate schema to find a key.""" for schema_key in schema: if schema_key == key_name: return schema_key.default() raise KeyError(f"{key_name} not found in schema")
Mock discovery service.
def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} return disco
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="Jellyfin", domain=DOMAIN, data={ CONF_URL: TEST_URL, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, }, unique_id="USER-UUID", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.jellyfin.async_setup_entry", return_value=True ) as setup_mock: yield setup_mock
Mock generating device id.
def mock_client_device_id() -> Generator[None, MagicMock, None]: """Mock generating device id.""" with patch( "homeassistant.components.jellyfin.config_flow._generate_client_device_id" ) as id_mock: id_mock.return_value = "TEST-UUID" yield id_mock
Return a mocked ConnectionManager.
def mock_auth() -> MagicMock: """Return a mocked ConnectionManager.""" jf_auth = create_autospec(ConnectionManager) jf_auth.connect_to_address.return_value = load_json_fixture( "auth-connect-address.json" ) jf_auth.login.return_value = load_json_fixture("auth-login.json") return jf_auth
Return a mocked API.
def mock_api() -> MagicMock: """Return a mocked API.""" jf_api = create_autospec(API) jf_api.get_user_settings.return_value = load_json_fixture("get-user-settings.json") jf_api.sessions.return_value = load_json_fixture("sessions.json") jf_api.artwork.side_effect = api_artwork_side_effect jf_api.audio_url.side_effect = api_audio_url_side_effect jf_api.video_url.side_effect = api_video_url_side_effect jf_api.user_items.side_effect = api_user_items_side_effect jf_api.get_item.side_effect = api_get_item_side_effect jf_api.get_media_folders.return_value = load_json_fixture("get-media-folders.json") jf_api.user_items.side_effect = api_user_items_side_effect return jf_api
Return a mocked JellyfinClient.
def mock_config() -> MagicMock: """Return a mocked JellyfinClient.""" jf_config = create_autospec(Config) jf_config.data = {"auth.server": "http://localhost"} return jf_config
Return a mocked JellyfinClient.
def mock_client( mock_config: MagicMock, mock_auth: MagicMock, mock_api: MagicMock ) -> MagicMock: """Return a mocked JellyfinClient.""" jf_client = create_autospec(JellyfinClient) jf_client.auth = mock_auth jf_client.config = mock_config jf_client.jellyfin = mock_api return jf_client
Return a mocked Jellyfin.
def mock_jellyfin(mock_client: MagicMock) -> Generator[None, MagicMock, None]: """Return a mocked Jellyfin.""" with patch( "homeassistant.components.jellyfin.client_wrapper.Jellyfin", autospec=True ) as jellyfin_mock: jf = jellyfin_mock.return_value jf.get_client.return_value = mock_client yield jf
Handle variable responses for artwork method.
def api_artwork_side_effect(*args, **kwargs): """Handle variable responses for artwork method.""" item_id = args[0] art = args[1] ext = "jpg" return f"http://localhost/Items/{item_id}/Images/{art}.{ext}"
Handle variable responses for audio_url method.
def api_audio_url_side_effect(*args, **kwargs): """Handle variable responses for audio_url method.""" item_id = args[0] return f"http://localhost/Audio/{item_id}/universal?UserId=test-username,DeviceId=TEST-UUID,MaxStreamingBitrate=140000000"
Handle variable responses for video_url method.
def api_video_url_side_effect(*args, **kwargs): """Handle variable responses for video_url method.""" item_id = args[0] return f"http://localhost/Videos/{item_id}/stream?static=true,DeviceId=TEST-UUID,api_key=TEST-API-KEY"
Handle variable responses for get_item method.
def api_get_item_side_effect(*args): """Handle variable responses for get_item method.""" return load_json_fixture("get-item-collection.json")
Handle variable responses for items method.
def api_user_items_side_effect(*args, **kwargs): """Handle variable responses for items method.""" params = kwargs.get("params", {}) if kwargs else {} if "parentId" in params: return load_json_fixture("user-items-parent-id.json") return load_json_fixture("user-items.json")
Load JSON fixture on-demand.
def load_json_fixture(filename: str) -> Any: """Load JSON fixture on-demand.""" return json.loads(load_fixture(f"jellyfin/{filename}"))
Make test params for NYC.
def make_nyc_test_params(dtime, results, havdalah_offset=0): """Make test params for NYC.""" if isinstance(results, dict): time_zone = dt_util.get_time_zone("America/New_York") results = { key: value.replace(tzinfo=time_zone) if isinstance(value, datetime) else value for key, value in results.items() } return ( dtime, jewish_calendar.CANDLE_LIGHT_DEFAULT, havdalah_offset, True, "America/New_York", NYC_LATLNG.lat, NYC_LATLNG.lng, results, )
Make test params for Jerusalem.
def make_jerusalem_test_params(dtime, results, havdalah_offset=0): """Make test params for Jerusalem.""" if isinstance(results, dict): time_zone = dt_util.get_time_zone("Asia/Jerusalem") results = { key: value.replace(tzinfo=time_zone) if isinstance(value, datetime) else value for key, value in results.items() } return ( dtime, jewish_calendar.CANDLE_LIGHT_DEFAULT, havdalah_offset, False, "Asia/Jerusalem", JERUSALEM_LATLNG.lat, JERUSALEM_LATLNG.lng, results, )
Return a mocked JVC Projector device.
def fixture_mock_device(request) -> Generator[None, AsyncMock, None]: """Return a mocked JVC Projector device.""" target = "homeassistant.components.jvc_projector.JvcProjector" if hasattr(request, "param"): target = request.param with patch(target, autospec=True) as mock: device = mock.return_value device.host = MOCK_HOST device.port = MOCK_PORT device.mac = MOCK_MAC device.model = MOCK_MODEL device.get_state.return_value = {"power": "standby", "input": "hdmi1"} yield device
Return a mock config entry.
def fixture_mock_config_entry() -> MockConfigEntry: """Return a mock config entry.""" return MockConfigEntry( domain=DOMAIN, unique_id=MOCK_MAC, version=1, data={ CONF_HOST: MOCK_HOST, CONF_PORT: MOCK_PORT, CONF_PASSWORD: MOCK_PASSWORD, }, )
Return a mocked Kaleidescape device.
def fixture_mock_device() -> Generator[None, AsyncMock, None]: """Return a mocked Kaleidescape device.""" with patch( "homeassistant.components.kaleidescape.KaleidescapeDevice", autospec=True ) as mock: host = MOCK_HOST device = mock.return_value device.dispatcher = Dispatcher() device.host = host device.port = 10000 device.serial_number = MOCK_SERIAL device.is_connected = True device.is_server_only = False device.is_movie_player = True device.is_music_player = False device.system = System( ip_address=host, serial_number=MOCK_SERIAL, type="Strato", protocol=16, kos_version="10.4.2-19218", friendly_name=f"Device {MOCK_SERIAL}", movie_zones=1, music_zones=1, ) device.power = Power(state="standby", readiness="disabled", zone=["available"]) device.movie = Movie() device.automation = Automation() yield device
Return a mock config entry.
def fixture_mock_config_entry() -> MockConfigEntry: """Return a mock config entry.""" return MockConfigEntry( domain=DOMAIN, unique_id=MOCK_SERIAL, version=1, data={CONF_HOST: MOCK_HOST}, )
Mock connection routine.
def mock_keenetic_connect(): """Mock connection routine.""" with patch("ndms2_client.client.Client.get_router_info") as mock_get_router_info: mock_get_router_info.return_value = RouterInfo( name=MOCK_NAME, fw_version="3.0.4", fw_channel="stable", model="mock", hw_version="0000", manufacturer="pytest", vendor="foxel", region="RU", ) yield
Mock connection routine.
def mock_keenetic_connect_failed(): """Mock connection routine.""" with patch( "ndms2_client.client.Client.get_router_info", side_effect=ConnectionException("Mocked failure"), ): yield
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Patch MicroBot API.
def patch_microbot_api(): """Patch MicroBot API.""" return patch( "homeassistant.components.keymitt_ble.config_flow.MicroBotApiClient", AsyncMock )
Patch async setup entry to return True.
def patch_async_setup_entry(return_value=True): """Patch async setup entry to return True.""" return patch( "homeassistant.components.keymitt_ble.async_setup_entry", return_value=return_value, )
Set up things to be run when tests are started.
def setup_comp(): """Set up things to be run when tests are started.""" with patch("homeassistant.components.kira.pykira.KiraReceiver"): yield
Set up temporary workdir.
def work_dir(): """Set up temporary workdir.""" work_dir = tempfile.mkdtemp() yield work_dir shutil.rmtree(work_dir, ignore_errors=True)
Mock add devices.
def add_entities(devices): """Mock add devices.""" DEVICES.extend(devices)
Test Kira's ability to send commands.
def test_service_call(hass: HomeAssistant) -> None: """Test Kira's ability to send commands.""" mock_kira = MagicMock() hass.data[kira.DOMAIN] = {kira.CONF_REMOTE: {}} hass.data[kira.DOMAIN][kira.CONF_REMOTE]["kira"] = mock_kira kira.setup_platform(hass, TEST_CONFIG, add_entities, DISCOVERY_INFO) assert len(DEVICES) == 1 remote = DEVICES[0] assert remote.name == "kira" command = ["FAKE_COMMAND"] device = "FAKE_DEVICE" commandTuple = (command[0], device) remote.send_command(device=device, command=command) mock_kira.sendCode.assert_called_with(commandTuple)
Mock add devices.
def add_entities(devices): """Mock add devices.""" DEVICES.extend(devices)
Ensure Kira sensor properly updates its attributes from callback.
def test_kira_sensor_callback( mock_schedule_update_ha_state, hass: HomeAssistant ) -> None: """Ensure Kira sensor properly updates its attributes from callback.""" mock_kira = MagicMock() hass.data[kira.DOMAIN] = {kira.CONF_SENSOR: {}} hass.data[kira.DOMAIN][kira.CONF_SENSOR]["kira"] = mock_kira kira.setup_platform(hass, TEST_CONFIG, add_entities, DISCOVERY_INFO) assert len(DEVICES) == 1 sensor = DEVICES[0] assert sensor.name == "kira" sensor.hass = hass codeName = "FAKE_CODE" deviceName = "FAKE_DEVICE" codeTuple = (codeName, deviceName) sensor._update_callback(codeTuple) mock_schedule_update_ha_state.assert_called() assert sensor.state == codeName assert sensor.extra_state_attributes == {kira.CONF_DEVICE: deviceName}
Test the initial parameters.
def test_setup_params(hass: HomeAssistant) -> None: """Test the initial parameters.""" state = hass.states.get(ENTITY_RESTART) assert state assert state.state == STATE_UNKNOWN
Mock history component loaded.
def mock_history(hass): """Mock history component loaded.""" hass.config.components.add("history")
Test the initial parameters.
def test_setup_params(hass: HomeAssistant) -> None: """Test the initial parameters.""" state = hass.states.get(ENTITY_DIRECT_MESSAGE) assert state assert state.state == STATE_UNKNOWN
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.kmtronic.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="KNX", domain=KNX_DOMAIN, data={ CONF_KNX_CONNECTION_TYPE: CONF_KNX_AUTOMATIC, CONF_KNX_RATE_LIMIT: CONF_KNX_DEFAULT_RATE_LIMIT, CONF_KNX_STATE_UPDATER: CONF_KNX_DEFAULT_STATE_UPDATER, CONF_KNX_MCAST_PORT: DEFAULT_MCAST_PORT, CONF_KNX_MCAST_GRP: DEFAULT_MCAST_GRP, CONF_KNX_INDIVIDUAL_ADDRESS: DEFAULT_ROUTING_IA, }, )
Mock KNX project data.
def load_knxproj(hass_storage): """Mock KNX project data.""" hass_storage[KNX_PROJECT_STORAGE_KEY] = { "version": 1, "data": FIXTURE_PROJECT_DATA, }
Mock KNX entry setup.
def fixture_knx_setup(): """Mock KNX entry setup.""" with ( patch("homeassistant.components.knx.async_setup", return_value=True), patch( "homeassistant.components.knx.async_setup_entry", return_value=True ) as mock_async_setup_entry, ): yield mock_async_setup_entry
Patch file upload. Yields the Keyring instance (return_value).
def patch_file_upload(return_value=FIXTURE_KEYRING, side_effect=None): """Patch file upload. Yields the Keyring instance (return_value).""" with ( patch( "homeassistant.components.knx.helpers.keyring.process_uploaded_file" ) as file_upload_mock, patch( "homeassistant.components.knx.helpers.keyring.sync_load_keyring", return_value=return_value, side_effect=side_effect, ), patch( "pathlib.Path.mkdir", ) as mkdir_mock, patch( "shutil.move", ) as shutil_move_mock, ): file_upload_mock.return_value.__enter__.return_value = Mock() yield return_value if side_effect: mkdir_mock.assert_not_called() shutil_move_mock.assert_not_called() else: mkdir_mock.assert_called_once() shutil_move_mock.assert_called_once()
Get mock gw descriptor.
def _gateway_descriptor( ip: str, port: int, supports_tunnelling_tcp: bool = False, requires_secure: bool = False, ) -> GatewayDescriptor: """Get mock gw descriptor.""" descriptor = GatewayDescriptor( name="Test", individual_address=GATEWAY_INDIVIDUAL_ADDRESS, ip_addr=ip, port=port, local_interface="eth0", local_ip="127.0.0.1", supports_routing=True, supports_tunnelling=True, supports_tunnelling_tcp=supports_tunnelling_tcp, ) descriptor.tunnelling_requires_secure = requires_secure descriptor.routing_requires_secure = requires_secure return descriptor
Track calls to a mock service.
def calls(hass: HomeAssistant) -> list[ServiceCall]: """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Assert that the mock telegrams are equal to the given telegrams. Omitting timestamp.
def assert_telegram_history(telegrams: list[TelegramDict]) -> bool: """Assert that the mock telegrams are equal to the given telegrams. Omitting timestamp.""" assert len(telegrams) == len(MOCK_TELEGRAMS) for index in range(len(telegrams)): test_telegram = copy(telegrams[index]) # don't modify the original comp_telegram = MOCK_TELEGRAMS[index] assert datetime.fromisoformat(test_telegram["timestamp"]) if isinstance(test_telegram["payload"], tuple): # JSON encodes tuples to lists test_telegram["payload"] = list(test_telegram["payload"]) assert test_telegram | {"timestamp": MOCK_TIMESTAMP} == comp_telegram return True
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")
Get Kodi connection.
def get_kodi_connection( host, port, ws_port, username, password, ssl=False, timeout=5, session=None ): """Get Kodi connection.""" if ws_port is None: return MockConnection() return MockWSConnection()
Return a mocked ConfigEntry for testing.
def mock_config_entry() -> MockConfigEntry: """Return a mocked ConfigEntry for testing.""" return MockConfigEntry( entry_id="2ab8dd92a62787ddfe213a67e09406bd", title="scb", domain="kostal_plenticore", data={"host": "192.168.1.2", "password": "SecretPassword"}, )
Set up a Plenticore mock with some default values.
def mock_plenticore() -> Generator[Plenticore, None, None]: """Set up a Plenticore mock with some default values.""" with patch( "homeassistant.components.kostal_plenticore.Plenticore", autospec=True ) as mock_api_class: # setup plenticore = mock_api_class.return_value plenticore.async_setup = AsyncMock() plenticore.async_setup.return_value = True plenticore.device_info = DeviceInfo( configuration_url="http://192.168.1.2", identifiers={("kostal_plenticore", "12345")}, manufacturer="Kostal", model="PLENTICORE plus 10", name="scb", sw_version="IOC: 01.45 MC: 01.46", ) plenticore.client = MagicMock() plenticore.client.get_version = AsyncMock() plenticore.client.get_version.return_value = VersionData( api_version="0.2.0", hostname="scb", name="PUCK RESTful API", sw_version="01.16.05025", ) plenticore.client.get_me = AsyncMock() plenticore.client.get_me.return_value = MeData( locked=False, active=True, authenticated=True, permissions=[], anonymous=False, role="USER", ) plenticore.client.get_process_data = AsyncMock() plenticore.client.get_settings = AsyncMock() yield plenticore
Return a mocked ApiClient instance.
def mock_apiclient() -> ApiClient: """Return a mocked ApiClient instance.""" apiclient = MagicMock(spec=ApiClient) apiclient.__aenter__.return_value = apiclient apiclient.__aexit__ = AsyncMock() return apiclient
Return a mocked ApiClient class.
def mock_apiclient_class(mock_apiclient) -> Generator[type[ApiClient], None, None]: """Return a mocked ApiClient class.""" with patch( "homeassistant.components.kostal_plenticore.config_flow.ApiClient", autospec=True, ) as mock_api_class: mock_api_class.return_value = mock_apiclient yield mock_api_class
Return a mocked ApiClient class.
def mock_apiclient() -> Generator[ApiClient, None, None]: """Return a mocked ApiClient class.""" with patch( "homeassistant.components.kostal_plenticore.helper.ExtendedApiClient", autospec=True, ) as mock_api_class: apiclient = MagicMock(spec=ExtendedApiClient) apiclient.__aenter__.return_value = apiclient apiclient.__aexit__ = AsyncMock() mock_api_class.return_value = apiclient yield apiclient
Return a patched ExtendedApiClient.
def mock_plenticore_client() -> Generator[ApiClient, None, None]: """Return a patched ExtendedApiClient.""" with patch( "homeassistant.components.kostal_plenticore.helper.ExtendedApiClient", autospec=True, ) as plenticore_client_class: yield plenticore_client_class.return_value
Add a setting value to the given Plenticore client. Returns a list with setting values which can be extended by test cases.
def mock_get_setting_values(mock_plenticore_client: ApiClient) -> list: """Add a setting value to the given Plenticore client. Returns a list with setting values which can be extended by test cases. """ mock_plenticore_client.get_settings.return_value = { "devices:local": [ SettingsData( min="5", max="100", default=None, access="readwrite", unit="%", id="Battery:MinSoc", type="byte", ), SettingsData( min="50", max="38000", default=None, access="readwrite", unit="W", id="Battery:MinHomeComsumption", type="byte", ), ], "scb:network": [ SettingsData( min="1", max="63", default=None, access="readwrite", unit=None, id="Hostname", type="string", ) ], } # this values are always retrieved by the integration on startup setting_values = [ { "devices:local": { "Properties:SerialNo": "42", "Branding:ProductName1": "PLENTICORE", "Branding:ProductName2": "plus 10", "Properties:VersionIOC": "01.45", "Properties:VersionMC": " 01.46", }, "scb:network": {"Hostname": "scb"}, } ] mock_plenticore_client.get_setting_values.side_effect = setting_values return setting_values
Patch the call rate limit sleep time.
def mock_call_rate_limit_sleep(): """Patch the call rate limit sleep time.""" with patch("homeassistant.components.kraken.CALL_RATE_LIMIT_SLEEP", new=0): yield
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.lacrosse_view.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Return the default mocked config entry.
def mock_config_entry( hass: HomeAssistant, mock_lamarzocco: MagicMock ) -> MockConfigEntry: """Return the default mocked config entry.""" entry = MockConfigEntry( title="My LaMarzocco", domain=DOMAIN, data=USER_INPUT | { CONF_MACHINE: mock_lamarzocco.serial_number, CONF_HOST: "host", CONF_NAME: "name", CONF_MAC: "mac", }, unique_id=mock_lamarzocco.serial_number, ) entry.add_to_hass(hass) return entry
Return the device fixture for a specific device.
def device_fixture() -> LaMarzoccoModel: """Return the device fixture for a specific device.""" return LaMarzoccoModel.GS3_AV
Return a mocked LM client.
def mock_lamarzocco( request: pytest.FixtureRequest, device_fixture: LaMarzoccoModel ) -> Generator[MagicMock, None, None]: """Return a mocked LM client.""" model_name = device_fixture (serial_number, true_model_name) = MODEL_DICT[model_name] with ( patch( "homeassistant.components.lamarzocco.coordinator.LaMarzoccoClient", autospec=True, ) as lamarzocco_mock, patch( "homeassistant.components.lamarzocco.config_flow.LaMarzoccoClient", new=lamarzocco_mock, ), ): lamarzocco = lamarzocco_mock.return_value lamarzocco.machine_info = { "machine_name": serial_number, "serial_number": serial_number, } lamarzocco.model_name = model_name lamarzocco.true_model_name = true_model_name lamarzocco.machine_name = serial_number lamarzocco.serial_number = serial_number lamarzocco.firmware_version = "1.1" lamarzocco.latest_firmware_version = "1.2" lamarzocco.gateway_version = "v2.2-rc0" lamarzocco.latest_gateway_version = "v3.1-rc4" lamarzocco.update_firmware.return_value = True lamarzocco.current_status = load_json_object_fixture( "current_status.json", DOMAIN ) lamarzocco.config = load_json_object_fixture("config.json", DOMAIN) lamarzocco.statistics = load_json_array_fixture("statistics.json", DOMAIN) lamarzocco.schedule = load_json_array_fixture("schedule.json", DOMAIN) lamarzocco.get_all_machines.return_value = [ (serial_number, model_name), ] lamarzocco.check_local_connection.return_value = True lamarzocco.initialized = False lamarzocco.websocket_connected = True async def websocket_connect_mock( callback: MagicMock, use_sigterm_handler: MagicMock ) -> None: """Mock the websocket connect method.""" return None lamarzocco.lm_local_api.websocket_connect = websocket_connect_mock lamarzocco.lm_bluetooth = MagicMock() lamarzocco.lm_bluetooth.address = "AA:BB:CC:DD:EE:FF" yield lamarzocco
Remove the local connection.
def remove_local_connection( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> MockConfigEntry: """Remove the local connection.""" data = mock_config_entry.data.copy() del data[CONF_HOST] hass.config_entries.async_update_entry(mock_config_entry, data=data) return mock_config_entry
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Return a mocked BluetoothServiceInfo.
def get_bluetooth_service_info( model: LaMarzoccoModel, serial: str ) -> BluetoothServiceInfo: """Return a mocked BluetoothServiceInfo.""" if model in (LaMarzoccoModel.GS3_AV, LaMarzoccoModel.GS3_MP): name = f"GS3_{serial}" elif model == LaMarzoccoModel.LINEA_MINI: name = f"MINI_{serial}" elif model == LaMarzoccoModel.LINEA_MICRA: name = f"MICRA_{serial}" return BluetoothServiceInfo( name=name, address="aa:bb:cc:dd:ee:ff", rssi=-63, manufacturer_data={}, service_data={}, service_uuids=[], source="local", )
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="My LaMetric", domain=DOMAIN, data={ CONF_HOST: "127.0.0.2", CONF_API_KEY: "mock-from-fixture", CONF_MAC: "AA:BB:CC:DD:EE:FF", }, unique_id="SA110405124500W00BS9", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.lametric.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup