response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Device class, which should be returned by the get_devices api call.
def device_fixture() -> str: """Device class, which should be returned by the get_devices api call.""" return "yna5x1"
Mock the authenticator.
def mock_authenticator(device_fixture: str) -> Generator[Mock, None, None]: """Mock the authenticator.""" with ( patch( "homeassistant.components.ecovacs.controller.Authenticator", autospec=True, ) as mock, patch( "homeassistant.components.ecovacs.config_flow.Authenticator", new=mock, ), ): authenticator = mock.return_value authenticator.authenticate.return_value = Credentials("token", "user_id", 0) devices = [ load_json_object_fixture(f"devices/{device_fixture}/device.json", DOMAIN) ] async def post_authenticated( path: str, json: dict[str, Any], *, query_params: dict[str, Any] | None = None, headers: dict[str, Any] | None = None, ) -> dict[str, Any]: match path: case const.PATH_API_APPSVR_APP: return {"code": 0, "devices": devices, "errno": "0"} case const.PATH_API_USERS_USER: return {"todo": "result", "result": "ok", "devices": devices} case _: raise ApiError("Path not mocked: {path}") authenticator.post_authenticated.side_effect = post_authenticated yield authenticator
Mock authenticator.authenticate.
def mock_authenticator_authenticate(mock_authenticator: Mock) -> AsyncMock: """Mock authenticator.authenticate.""" return mock_authenticator.authenticate
Mock the MQTT client.
def mock_mqtt_client(mock_authenticator: Mock) -> Mock: """Mock the MQTT client.""" with ( patch( "homeassistant.components.ecovacs.controller.MqttClient", autospec=True, ) as mock, patch( "homeassistant.components.ecovacs.config_flow.MqttClient", new=mock, ), ): client = mock.return_value client._authenticator = mock_authenticator client.subscribe.return_value = lambda: None yield client
Mock the device execute function.
def mock_device_execute() -> AsyncMock: """Mock the device execute function.""" with patch.object( Device, "_execute_command", return_value=True ) as mock_device_execute: yield mock_device_execute
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return PLATFORMS
Get the controller for the config entry.
def controller( hass: HomeAssistant, init_integration: MockConfigEntry ) -> EcovacsController: """Get the controller for the config entry.""" return hass.data[DOMAIN][init_integration.entry_id]
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.BINARY_SENSOR
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.BUTTON
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.EVENT
Mock the API client.
def mock_api_client(mock_authenticator: Mock) -> Mock: """Mock the API client.""" with patch( "homeassistant.components.ecovacs.controller.ApiClient", autospec=True, ) as mock_api_client: yield mock_api_client.return_value
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.LAWN_MOWER
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.NUMBER
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.SELECT
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.SENSOR
Platforms, which should be loaded during the test.
def platforms() -> Platform | list[Platform]: """Platforms, which should be loaded during the test.""" return Platform.SWITCH
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.edl21.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Make sure all entities are enabled.
def enable_all_entities(entity_registry_enabled_by_default): """Make sure all entities are enabled."""
Create Efergy entry in Home Assistant.
def create_entry(hass: HomeAssistant, token: str = TOKEN) -> MockConfigEntry: """Create Efergy entry in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=HID, data={CONF_API_KEY: token}, ) entry.add_to_hass(hass) return entry
Fixture for setting up the integration.
def component_setup( hass: HomeAssistant, config_entry: MockConfigEntry ) -> ComponentSetup: """Fixture for setting up the integration.""" async def _setup_func() -> bool: assert await async_setup_component(hass, "application_credentials", {}) await hass.async_block_till_done() await async_import_client_credential( hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET), DOMAIN, ) await hass.async_block_till_done() config_entry.add_to_hass(hass) result = await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return result return _setup_func
Create mocked config entry.
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry: """Create mocked config entry.""" return MockConfigEntry( title="Electric Kiwi", domain=DOMAIN, data={ "id": "12345", "auth_implementation": DOMAIN, "token": { "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "type": "Bearer", "expires_in": 60, "expires_at": time() + 60, }, }, unique_id=DOMAIN, )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.electric_kiwi.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Patch access to electric kiwi access token.
def electric_kiwi_auth() -> YieldFixture: """Patch access to electric kiwi access token.""" with patch( "homeassistant.components.electric_kiwi.api.AsyncConfigEntryAuth" ) as mock_auth: mock_auth.return_value.async_get_access_token = AsyncMock("auth_token") yield mock_auth
Mock ek api and return values.
def ek_api() -> YieldFixture: """Mock ek api and return values.""" with patch( "homeassistant.components.electric_kiwi.ElectricKiwiApi", autospec=True ) as mock_ek_api: mock_ek_api.return_value.customer_number = 123456 mock_ek_api.return_value.connection_id = 123456 mock_ek_api.return_value.set_active_session.return_value = None mock_ek_api.return_value.get_hop_intervals.return_value = ( HopIntervals.from_dict( load_json_value_fixture("hop_intervals.json", DOMAIN) ) ) mock_ek_api.return_value.get_hop.return_value = Hop.from_dict( load_json_value_fixture("get_hop.json", DOMAIN) ) mock_ek_api.return_value.get_account_balance.return_value = ( AccountBalance.from_dict( load_json_value_fixture("account_balance.json", DOMAIN) ) ) yield mock_ek_api
Restore default timezone.
def restore_timezone(): """Restore default timezone.""" yield dt_util.set_default_time_zone(DEFAULT_TIME_ZONE)
Return the device fixtures for a specific device.
def device_fixtures() -> str: """Return the device fixtures for a specific device.""" return "key-light"
Return the state variant to load for a device.
def state_variant() -> str: """Return the state variant to load for a device.""" return "state"
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="CN11A1A00001", domain=DOMAIN, data={ CONF_HOST: "127.0.0.1", CONF_MAC: "AA:BB:CC:DD:EE:FF", CONF_PORT: 9123, }, unique_id="CN11A1A00001", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.elgato.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Mock that Home Assistant is currently onboarding.
def mock_onboarding() -> Generator[None, MagicMock, None]: """Mock that Home Assistant is currently onboarding.""" with patch( "homeassistant.components.onboarding.async_is_onboarded", return_value=False, ) as mock_onboarding: yield mock_onboarding
Return a mocked Elgato client.
def mock_elgato( device_fixtures: str, state_variant: str ) -> Generator[None, MagicMock, None]: """Return a mocked Elgato client.""" with ( patch( "homeassistant.components.elgato.coordinator.Elgato", autospec=True ) as elgato_mock, patch("homeassistant.components.elgato.config_flow.Elgato", new=elgato_mock), ): elgato = elgato_mock.return_value elgato.info.return_value = Info.from_json( load_fixture(f"{device_fixtures}/info.json", DOMAIN) ) elgato.state.return_value = State.from_json( load_fixture(f"{device_fixtures}/{state_variant}.json", DOMAIN) ) elgato.settings.return_value = Settings.from_json( load_fixture(f"{device_fixtures}/settings.json", DOMAIN) ) # This may, or may not, be a battery-powered device if get_fixture_path(f"{device_fixtures}/battery.json", DOMAIN).exists(): elgato.has_battery.return_value = True elgato.battery.return_value = BatteryInfo.from_json( load_fixture(f"{device_fixtures}/battery.json", DOMAIN) ) else: elgato.has_battery.return_value = False elgato.battery.side_effect = ElgatoNoBatteryError yield elgato
Mock m1lib Elk.
def mock_elk(invalid_auth=None, sync_complete=None, exception=None): """Mock m1lib Elk.""" def handler_callbacks(type_, callback): nonlocal invalid_auth, sync_complete if exception: raise exception if type_ == "login": callback(not invalid_auth) elif type_ == "sync_complete" and sync_complete: callback() mocked_elk = MagicMock() mocked_elk.add_handler.side_effect = handler_callbacks return mocked_elk
Configure httpx fixture for cloud API communication.
def httpx_mock_cloud_fixture(requests_mock): """Configure httpx fixture for cloud API communication.""" with respx.mock(base_url=BASE_URL, assert_all_called=False) as respx_mock: # Mock Login POST. login_route = respx_mock.post(f"/{ENDPOINT_LOGIN}", name="login") login_route.return_value = Response( 200, json=json.loads(load_fixture("cloud/login.json", "elmax")) ) # Mock Device list GET. list_devices_route = respx_mock.get(f"/{ENDPOINT_DEVICES}", name="list_devices") list_devices_route.return_value = Response( 200, json=json.loads(load_fixture("cloud/list_devices.json", "elmax")) ) # Mock Panel GET. get_panel_route = respx_mock.get( f"/{ENDPOINT_DISCOVERY}/{MOCK_PANEL_ID}/{MOCK_PANEL_PIN}", name="get_panel" ) get_panel_route.return_value = Response( 200, json=json.loads(load_fixture("cloud/get_panel.json", "elmax")) ) yield respx_mock
Configure httpx fixture for direct Panel-API communication.
def httpx_mock_direct_fixture(requests_mock): """Configure httpx fixture for direct Panel-API communication.""" with respx.mock( base_url=MOCK_DIRECT_BASE_URI, assert_all_called=False ) as respx_mock: # Mock Login POST. login_route = respx_mock.post(f"/api/v2/{ENDPOINT_LOGIN}", name="login") login_route.return_value = Response( 200, json=json.loads(load_fixture("direct/login.json", "elmax")) ) # Mock Device list GET. list_devices_route = respx_mock.get( f"/api/v2/{ENDPOINT_DISCOVERY}", name="discovery_panel" ) list_devices_route.return_value = Response( 200, json=json.loads(load_fixture("direct/discovery_panel.json", "elmax")) ) yield respx_mock
Patch elmax library to return a specific PEM for SSL communication.
def elmax_mock_direct_cert(requests_mock): """Patch elmax library to return a specific PEM for SSL communication.""" with patch( "elmax_api.http.GenericElmax.retrieve_server_certificate", return_value=load_fixture("direct/cert.pem", "elmax"), ) as patched_ssl_get_cert: yield patched_ssl_get_cert
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.elvia.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
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."""
Patch async_create_upnp_datagram_endpoint.
def patch_upnp(): """Patch async_create_upnp_datagram_endpoint.""" return patch( "homeassistant.components.emulated_hue.async_create_upnp_datagram_endpoint" )
Override the hue config with specific entity numbers.
def _mock_hue_endpoints( hass: HomeAssistant, conf: ConfigType, entity_numbers: dict[str, str] ) -> None: """Override the hue config with specific entity numbers.""" web_app = hass.http.app config = Config(hass, conf, "127.0.0.1") config.numbers = entity_numbers HueUsernameView().register(hass, web_app, web_app.router) HueAllLightsStateView(config).register(hass, web_app, web_app.router) HueOneLightStateView(config).register(hass, web_app, web_app.router) HueOneLightChangeView(config).register(hass, web_app, web_app.router) HueAllGroupsStateView(config).register(hass, web_app, web_app.router) HueGroupView(config).register(hass, web_app, web_app.router) HueFullStateView(config).register(hass, web_app, web_app.router) HueConfigView(config).register(hass, web_app, web_app.router)
Test config adheres to the type.
def test_config_alexa_entity_id_to_number() -> None: """Test config adheres to the type.""" conf = Config(None, {"type": "alexa"}, "127.0.0.1") number = conf.entity_id_to_number("light.test") assert number == "light.test" number = conf.entity_id_to_number("light.test") assert number == "light.test" number = conf.entity_id_to_number("light.test2") assert number == "light.test2" entity_id = conf.number_to_entity_id("light.test") assert entity_id == "light.test"
Return aiohttp_client and allow opening sockets.
def aiohttp_client(event_loop, aiohttp_client, socket_enabled): """Return aiohttp_client and allow opening sockets.""" return aiohttp_client
Return a hue API client.
def hue_client(aiohttp_client): """Return a hue API client.""" app = web.Application() with unittest.mock.patch( "homeassistant.components.emulated_hue.web.Application", return_value=app ): async def client(): """Return an authenticated client.""" return await aiohttp_client(app) yield client
Tests the UPnP basic discovery response.
def test_upnp_discovery_basic() -> None: """Tests the UPnP basic discovery response.""" upnp_responder_protocol = upnp.UPNPResponderProtocol(None, None, "192.0.2.42", 8080) mock_transport = MockTransport() upnp_responder_protocol.transport = mock_transport """Original request emitted by the Hue Bridge v1 app.""" request = """M-SEARCH * HTTP/1.1 HOST:239.255.255.250:1900 ST:ssdp:all Man:"ssdp:discover" MX:3 """ encoded_request = request.replace("\n", "\r\n").encode("utf-8") upnp_responder_protocol.datagram_received(encoded_request, 1234) expected_response = """HTTP/1.1 200 OK CACHE-CONTROL: max-age=60 EXT: LOCATION: http://192.0.2.42:8080/description.xml SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/1.16.0 hue-bridgeid: 001788FFFE23BFC2 ST: urn:schemas-upnp-org:device:basic:1 USN: uuid:2f402f80-da50-11e1-9b23-001788255acc """ expected_send = expected_response.replace("\n", "\r\n").encode("utf-8") assert mock_transport.sends == [(expected_send, 1234)]
Tests the UPnP rootdevice discovery response.
def test_upnp_discovery_rootdevice() -> None: """Tests the UPnP rootdevice discovery response.""" upnp_responder_protocol = upnp.UPNPResponderProtocol(None, None, "192.0.2.42", 8080) mock_transport = MockTransport() upnp_responder_protocol.transport = mock_transport """Original request emitted by Busch-Jaeger free@home SysAP.""" request = """M-SEARCH * HTTP/1.1 HOST: 239.255.255.250:1900 MAN: "ssdp:discover" MX: 40 ST: upnp:rootdevice """ encoded_request = request.replace("\n", "\r\n").encode("utf-8") upnp_responder_protocol.datagram_received(encoded_request, 1234) expected_response = """HTTP/1.1 200 OK CACHE-CONTROL: max-age=60 EXT: LOCATION: http://192.0.2.42:8080/description.xml SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/1.16.0 hue-bridgeid: 001788FFFE23BFC2 ST: upnp:rootdevice USN: uuid:2f402f80-da50-11e1-9b23-001788255acc::upnp:rootdevice """ expected_send = expected_response.replace("\n", "\r\n").encode("utf-8") assert mock_transport.sends == [(expected_send, 1234)]
Tests the UPnP does not response on an invalid request.
def test_upnp_no_response() -> None: """Tests the UPnP does not response on an invalid request.""" upnp_responder_protocol = upnp.UPNPResponderProtocol(None, None, "192.0.2.42", 8080) mock_transport = MockTransport() upnp_responder_protocol.transport = mock_transport """Original request emitted by the Hue Bridge v1 app.""" request = """INVALID * HTTP/1.1 HOST:239.255.255.250:1900 ST:ssdp:all Man:"ssdp:discover" MX:3 """ encoded_request = request.replace("\n", "\r\n").encode("utf-8") upnp_responder_protocol.datagram_received(encoded_request, 1234) assert mock_transport.sends == []
Return a nested dict value or None if it doesn't exist.
def nested_value(ndict, *keys): """Return a nested dict value or None if it doesn't exist.""" if len(keys) == 0: return ndict key = keys[0] if not isinstance(ndict, dict) or key not in ndict: return None return nested_value(ndict[key], *keys[1:])
Return valid user input.
def demo_config_data() -> dict: """Return valid user input.""" return {CONF_DEVICE_API_ID: DEMO_CONFIG_DATA[CONF_DEVICE_API_ID]}
Return a valid egps config entry.
def valid_config_entry() -> MockConfigEntry: """Return a valid egps config entry.""" return MockConfigEntry( domain=DOMAIN, data=DEMO_CONFIG_DATA, unique_id=DEMO_CONFIG_DATA[CONF_DEVICE_API_ID], )
Fixture for a mocked FakePowerStrip.
def get_pyegps_device_mock() -> MagicMock: """Fixture for a mocked FakePowerStrip.""" fkObj = FakePowerStrip( devId=DEMO_CONFIG_DATA[CONF_DEVICE_API_ID], number_of_sockets=4 ) fkObj.release = lambda: True fkObj._status = [0, 1, 0, 1] usb_device_mock = MagicMock(wraps=fkObj) usb_device_mock.get_device_type.return_value = "PowerStrip" usb_device_mock.numberOfSockets = 4 usb_device_mock.device_id = DEMO_CONFIG_DATA[CONF_DEVICE_API_ID] usb_device_mock.manufacturer = "Energenie" usb_device_mock.name = "MockedUSBDevice" return usb_device_mock
Fixture to patch the `get_device` api method.
def patch_get_device(pyegps_device_mock: MagicMock) -> Generator[MagicMock, None, None]: """Fixture to patch the `get_device` api method.""" with ( patch("homeassistant.components.energenie_power_sockets.get_device") as m1, patch( "homeassistant.components.energenie_power_sockets.config_flow.get_device", new=m1, ) as mock, ): mock.return_value = pyegps_device_mock yield mock
Fixture to patch the `search_for_devices` api method.
def patch_search_devices( pyegps_device_mock: MagicMock, ) -> Generator[MagicMock, None, None]: """Fixture to patch the `search_for_devices` api method.""" with patch( "homeassistant.components.energenie_power_sockets.config_flow.search_for_devices", return_value=[pyegps_device_mock], ) as mock: yield mock
Freeze clock for tests.
def frozen_time(freezer): """Freeze clock for tests.""" freezer.move_to("2022-04-19 07:53:05") return freezer
Get statistics for a certain entity, or None if there is none.
def get_statistics_for_entity(statistics_results, entity_id): """Get statistics for a certain entity, or None if there is none.""" for statistics_result in statistics_results: if statistics_result["meta"]["statistic_id"] == entity_id: return statistics_result return None
Mock recorder.is_entity_recorded.
def mock_is_entity_recorded(): """Mock recorder.is_entity_recorded.""" mocks = {} with patch( "homeassistant.components.recorder.is_entity_recorded", side_effect=lambda hass, entity_id: mocks.get(entity_id, True), ): yield mocks
Mock recorder.statistics.get_metadata.
def mock_get_metadata(): """Mock recorder.statistics.get_metadata.""" mocks = {} def _get_metadata(_hass, *, statistic_ids): result = {} for statistic_id in statistic_ids: if statistic_id in mocks: if mocks[statistic_id] is not None: result[statistic_id] = mocks[statistic_id] else: result[statistic_id] = (1, {}) return result with patch( "homeassistant.components.recorder.statistics.get_metadata", wraps=_get_metadata, ): yield mocks
Mock an energy platform.
def mock_energy_platform(hass): """Mock an energy platform.""" hass.config.components.add("some_domain") mock_platform( hass, "some_domain.energy", Mock( async_get_solar_forecast=AsyncMock( return_value={ "wh_hours": { "2021-06-27T13:00:00+00:00": 12, "2021-06-27T14:00:00+00:00": 8, } } ) ), )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.energyzero.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="energy", domain=DOMAIN, data={}, unique_id="unique_thingy", )
Return a mocked EnergyZero client.
def mock_energyzero() -> Generator[MagicMock, None, None]: """Return a mocked EnergyZero client.""" with patch( "homeassistant.components.energyzero.coordinator.EnergyZero", autospec=True ) as energyzero_mock: client = energyzero_mock.return_value client.energy_prices.return_value = Electricity.from_dict( json.loads(load_fixture("today_energy.json", DOMAIN)) ) client.gas_prices.return_value = Gas.from_dict( json.loads(load_fixture("today_gas.json", DOMAIN)) ) yield client
Fixture for the config entry.
def config_entry_data( mock_config_entry: MockConfigEntry, request: pytest.FixtureRequest ) -> dict[str, str]: """Fixture for the config entry.""" if "config_entry" in request.param and request.param["config_entry"] is True: return {"config_entry": mock_config_entry.entry_id} return request.param
Define a config entry fixture.
def config_entry_fixture(hass: HomeAssistant, config, serial_number): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, entry_id="45a36e55aaddb2007c5f6602e0c38e72", title=f"Envoy {serial_number}" if serial_number else "Envoy", unique_id=serial_number, data=config, ) entry.add_to_hass(hass) return entry
Define a config entry data fixture.
def config_fixture(): """Define a config entry data fixture.""" return { CONF_HOST: "1.1.1.1", CONF_NAME: "Envoy 1234", CONF_USERNAME: "test-username", CONF_PASSWORD: "test-password", }
Define a mocked Envoy fixture.
def mock_envoy_fixture( serial_number, mock_authenticate, mock_setup, mock_auth, ): """Define a mocked Envoy fixture.""" mock_envoy = Mock(spec=Envoy) mock_envoy.serial_number = serial_number mock_envoy.firmware = "7.1.2" mock_envoy.part_number = "123456789" mock_envoy.envoy_model = "Envoy, phases: 3, phase mode: three, net-consumption CT, production CT, storage CT" mock_envoy.authenticate = mock_authenticate mock_envoy.setup = mock_setup mock_envoy.auth = mock_auth mock_envoy.supported_features = SupportedFeatures( SupportedFeatures.INVERTERS | SupportedFeatures.PRODUCTION | SupportedFeatures.PRODUCTION | SupportedFeatures.METERING | SupportedFeatures.THREEPHASE | SupportedFeatures.CTMETERS ) mock_envoy.phase_mode = EnvoyPhaseMode.THREE mock_envoy.phase_count = 3 mock_envoy.active_phase_count = 3 mock_envoy.ct_meter_count = 3 mock_envoy.consumption_meter_type = CtType.NET_CONSUMPTION mock_envoy.production_meter_type = CtType.PRODUCTION mock_envoy.storage_meter_type = CtType.STORAGE mock_envoy.data = EnvoyData( system_consumption=EnvoySystemConsumption( watt_hours_last_7_days=1234, watt_hours_lifetime=1234, watt_hours_today=1234, watts_now=1234, ), system_production=EnvoySystemProduction( watt_hours_last_7_days=1234, watt_hours_lifetime=1234, watt_hours_today=1234, watts_now=1234, ), system_consumption_phases={ PhaseNames.PHASE_1: EnvoySystemConsumption( watt_hours_last_7_days=1321, watt_hours_lifetime=1322, watt_hours_today=1323, watts_now=1324, ), PhaseNames.PHASE_2: EnvoySystemConsumption( watt_hours_last_7_days=2321, watt_hours_lifetime=2322, watt_hours_today=2323, watts_now=2324, ), PhaseNames.PHASE_3: EnvoySystemConsumption( watt_hours_last_7_days=3321, watt_hours_lifetime=3322, watt_hours_today=3323, watts_now=3324, ), }, system_production_phases={ PhaseNames.PHASE_1: EnvoySystemProduction( watt_hours_last_7_days=1231, watt_hours_lifetime=1232, watt_hours_today=1233, watts_now=1234, ), PhaseNames.PHASE_2: EnvoySystemProduction( watt_hours_last_7_days=2231, watt_hours_lifetime=2232, watt_hours_today=2233, watts_now=2234, ), PhaseNames.PHASE_3: EnvoySystemProduction( watt_hours_last_7_days=3231, watt_hours_lifetime=3232, watt_hours_today=3233, watts_now=3234, ), }, ctmeter_production=EnvoyMeterData( eid="100000010", timestamp=1708006110, energy_delivered=11234, energy_received=12345, active_power=100, power_factor=0.11, voltage=111, current=0.2, frequency=50.1, state=CtState.ENABLED, measurement_type=CtType.PRODUCTION, metering_status=CtMeterStatus.NORMAL, status_flags=[ CtStatusFlags.PODUCTION_IMBALANCE, CtStatusFlags.POWER_ON_UNUSED_PHASE, ], ), ctmeter_consumption=EnvoyMeterData( eid="100000020", timestamp=1708006120, energy_delivered=21234, energy_received=22345, active_power=101, power_factor=0.21, voltage=112, current=0.3, frequency=50.2, state=CtState.ENABLED, measurement_type=CtType.NET_CONSUMPTION, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), ctmeter_storage=EnvoyMeterData( eid="100000030", timestamp=1708006120, energy_delivered=31234, energy_received=32345, active_power=103, power_factor=0.23, voltage=113, current=0.4, frequency=50.3, state=CtState.ENABLED, measurement_type=CtType.STORAGE, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), ctmeter_production_phases={ PhaseNames.PHASE_1: EnvoyMeterData( eid="100000011", timestamp=1708006111, energy_delivered=112341, energy_received=123451, active_power=20, power_factor=0.12, voltage=111, current=0.2, frequency=50.1, state=CtState.ENABLED, measurement_type=CtType.PRODUCTION, metering_status=CtMeterStatus.NORMAL, status_flags=[CtStatusFlags.PODUCTION_IMBALANCE], ), PhaseNames.PHASE_2: EnvoyMeterData( eid="100000012", timestamp=1708006112, energy_delivered=112342, energy_received=123452, active_power=30, power_factor=0.13, voltage=111, current=0.2, frequency=50.1, state=CtState.ENABLED, measurement_type=CtType.PRODUCTION, metering_status=CtMeterStatus.NORMAL, status_flags=[CtStatusFlags.POWER_ON_UNUSED_PHASE], ), PhaseNames.PHASE_3: EnvoyMeterData( eid="100000013", timestamp=1708006113, energy_delivered=112343, energy_received=123453, active_power=50, power_factor=0.14, voltage=111, current=0.2, frequency=50.1, state=CtState.ENABLED, measurement_type=CtType.PRODUCTION, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), }, ctmeter_consumption_phases={ PhaseNames.PHASE_1: EnvoyMeterData( eid="100000021", timestamp=1708006121, energy_delivered=212341, energy_received=223451, active_power=21, power_factor=0.22, voltage=112, current=0.3, frequency=50.2, state=CtState.ENABLED, measurement_type=CtType.NET_CONSUMPTION, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), PhaseNames.PHASE_2: EnvoyMeterData( eid="100000022", timestamp=1708006122, energy_delivered=212342, energy_received=223452, active_power=31, power_factor=0.23, voltage=112, current=0.3, frequency=50.2, state=CtState.ENABLED, measurement_type=CtType.NET_CONSUMPTION, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), PhaseNames.PHASE_3: EnvoyMeterData( eid="100000023", timestamp=1708006123, energy_delivered=212343, energy_received=223453, active_power=51, power_factor=0.24, voltage=112, current=0.3, frequency=50.2, state=CtState.ENABLED, measurement_type=CtType.NET_CONSUMPTION, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), }, ctmeter_storage_phases={ PhaseNames.PHASE_1: EnvoyMeterData( eid="100000031", timestamp=1708006121, energy_delivered=312341, energy_received=323451, active_power=22, power_factor=0.32, voltage=113, current=0.4, frequency=50.3, state=CtState.ENABLED, measurement_type=CtType.STORAGE, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), PhaseNames.PHASE_2: EnvoyMeterData( eid="100000032", timestamp=1708006122, energy_delivered=312342, energy_received=323452, active_power=33, power_factor=0.23, voltage=112, current=0.3, frequency=50.2, state=CtState.ENABLED, measurement_type=CtType.STORAGE, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), PhaseNames.PHASE_3: EnvoyMeterData( eid="100000033", timestamp=1708006123, energy_delivered=312343, energy_received=323453, active_power=53, power_factor=0.24, voltage=112, current=0.3, frequency=50.2, state=CtState.ENABLED, measurement_type=CtType.STORAGE, metering_status=CtMeterStatus.NORMAL, status_flags=[], ), }, inverters={ "1": EnvoyInverter( serial_number="1", last_report_date=1, last_report_watts=1, max_report_watts=1, ) }, raw={"varies_by": "firmware_version"}, ) mock_envoy.update = AsyncMock(return_value=mock_envoy.data) return mock_envoy
Define a mocked Envoy.authenticate fixture.
def mock_authenticate(): """Define a mocked Envoy.authenticate fixture.""" return AsyncMock()
Define a mocked EnvoyAuth fixture.
def mock_auth(serial_number): """Define a mocked EnvoyAuth fixture.""" token = jwt.encode( payload={"name": "envoy", "exp": 1907837780}, key="secret", algorithm="HS256" ) return EnvoyTokenAuth("127.0.0.1", token=token, envoy_serial=serial_number)
Define a mocked Envoy.setup fixture.
def mock_setup(): """Define a mocked Envoy.setup fixture.""" return AsyncMock()
Define a serial number fixture.
def serial_number_fixture(): """Define a serial number fixture.""" return "1234"
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")
Mark attributes to exclude from diagnostic snapshot.
def limit_diagnostic_attrs(prop, path) -> bool: """Mark attributes to exclude from diagnostic snapshot.""" return prop in TO_EXCLUDE
Mock the env_canada library.
def mocked_ec( station_id=FAKE_CONFIG[CONF_STATION], lat=FAKE_CONFIG[CONF_LATITUDE], lon=FAKE_CONFIG[CONF_LONGITUDE], lang=FAKE_CONFIG[CONF_LANGUAGE], update=None, metadata={"location": FAKE_TITLE}, ): """Mock the env_canada library.""" ec_mock = MagicMock() ec_mock.station_id = station_id ec_mock.lat = lat ec_mock.lon = lon ec_mock.language = lang ec_mock.metadata = metadata if update: ec_mock.update = update else: ec_mock.update = AsyncMock() return patch( "homeassistant.components.environment_canada.config_flow.ECWeather", return_value=ec_mock, )
Mock a successful service with multiple free & discount games.
def mock_service_multiple(): """Mock a successful service with multiple free & discount games.""" with patch( "homeassistant.components.epic_games_store.coordinator.EpicGamesStoreAPI" ) as service_mock: instance = service_mock.return_value instance.get_free_games = Mock(return_value=DATA_FREE_GAMES) yield service_mock
Mock a successful service with Christmas special case.
def mock_service_christmas_special(): """Mock a successful service with Christmas special case.""" with patch( "homeassistant.components.epic_games_store.coordinator.EpicGamesStoreAPI" ) as service_mock: instance = service_mock.return_value instance.get_free_games = Mock(return_value=DATA_FREE_GAMES_CHRISTMAS_SPECIAL) yield service_mock
Mock a successful service returning a not found attribute error with free & discount games.
def mock_service_attribute_not_found(): """Mock a successful service returning a not found attribute error with free & discount games.""" with patch( "homeassistant.components.epic_games_store.coordinator.EpicGamesStoreAPI" ) as service_mock: instance = service_mock.return_value instance.get_free_games = Mock(return_value=DATA_ERROR_ATTRIBUTE_NOT_FOUND) yield service_mock
Test game data format.
def test_format_game_data() -> None: """Test game data format.""" game_data = format_game_data(FREE_GAME, "fr") assert game_data assert game_data["title"] assert game_data["description"] assert game_data["released_at"] assert game_data["original_price"] assert game_data["publisher"] assert game_data["url"] assert game_data["img_portrait"] assert game_data["img_landscape"] assert game_data["discount_type"] == "free" assert game_data["discount_start_at"] assert game_data["discount_end_at"]
Test to get the game URL.
def test_get_game_url(raw_game_data: dict[str, Any], expected_result: bool) -> None: """Test to get the game URL.""" assert get_game_url(raw_game_data, "fr").endswith(expected_result)
Test if this game is free.
def test_is_free_game(raw_game_data: dict[str, Any], expected_result: bool) -> None: """Test if this game is free.""" assert is_free_game(raw_game_data) == expected_result
Build a fixture for the Epion API that connects successfully and returns one device.
def mock_epion(): """Build a fixture for the Epion API that connects successfully and returns one device.""" current_one_device_data = load_json_object_fixture( "epion/get_current_one_device.json" ) mock_epion_api = MagicMock() with ( patch( "homeassistant.components.epion.config_flow.Epion", return_value=mock_epion_api, ) as mock_epion_api, patch( "homeassistant.components.epion.Epion", return_value=mock_epion_api, ), ): mock_epion_api.return_value.get_current.return_value = current_one_device_data yield mock_epion_api
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Return a BluetoothServiceInfoBleak for use in testing.
def fake_service_info(): """Return a BluetoothServiceInfoBleak for use in testing.""" return BluetoothServiceInfoBleak( name="CC-RT-BLE", address=MAC, rssi=0, manufacturer_data={}, service_data={}, service_uuids=[], source="local", connectable=False, time=0, device=generate_ble_device(address=MAC, name="CC-RT-BLE", rssi=0), advertisement=AdvertisementData( local_name="CC-RT-BLE", manufacturer_data={}, service_data={}, service_uuids=[], rssi=0, tx_power=-127, platform_data=(), ), )
Mock discovery service.
def mock_discovery_service_fixture() -> AsyncMock: """Mock discovery service.""" discovery_service = AsyncMock() discovery_service.controllers = {} return discovery_service
Mock controller.
def mock_controller_fixture() -> MagicMock: """Mock controller.""" return MagicMock()
Mock start discovery service.
def _mock_start_discovery( discovery_service: MagicMock, controller: MagicMock ) -> Callable[[], Coroutine[None, None, None]]: """Mock start discovery service.""" async def do_discovered() -> None: """Call the listener callback.""" listener: DiscoveryServiceListener = discovery_service.call_args[0][0] listener.controller_discovered(controller) return do_discovered
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Auto mock zeroconf.
def esphome_mock_async_zeroconf(mock_async_zeroconf): """Auto mock zeroconf."""
Auto mock the tts cache.
def mock_tts(mock_tts_cache_dir): """Auto mock the tts cache."""
Return the default mocked config entry.
def mock_config_entry(hass) -> MockConfigEntry: """Return the default mocked config entry.""" config_entry = MockConfigEntry( title="ESPHome Device", entry_id="08d821dc059cf4f645cb024d32c8e708", domain=DOMAIN, data={ CONF_HOST: "192.168.1.2", CONF_PORT: 6053, CONF_PASSWORD: "pwd", CONF_NOISE_PSK: "12345678123456781234567812345678", CONF_DEVICE_NAME: "test", }, # ESPHome unique ids are lower case unique_id="11:22:33:44:55:aa", ) config_entry.add_to_hass(hass) return config_entry
Return the default mocked device info.
def mock_device_info() -> DeviceInfo: """Return the default mocked device info.""" return DeviceInfo( uses_password=False, name="test", legacy_bluetooth_proxy_version=0, # ESPHome mac addresses are UPPER case mac_address="11:22:33:44:55:AA", esphome_version="1.0.0", )
Mock APIClient.
def mock_client(mock_device_info) -> APIClient: """Mock APIClient.""" mock_client = Mock(spec=APIClient) def mock_constructor( address: str, port: int, password: str | None, *, client_info: str = "aioesphomeapi", keepalive: float = 15.0, zeroconf_instance: Zeroconf = None, noise_psk: str | None = None, expected_name: str | None = None, ): """Fake the client constructor.""" mock_client.host = address mock_client.port = port mock_client.password = password mock_client.zeroconf_instance = zeroconf_instance mock_client.noise_psk = noise_psk return mock_client mock_client.side_effect = mock_constructor mock_client.device_info = AsyncMock(return_value=mock_device_info) mock_client.connect = AsyncMock() mock_client.disconnect = AsyncMock() mock_client.list_entities_services = AsyncMock(return_value=([], [])) mock_client.address = "127.0.0.1" mock_client.api_version = APIVersion(99, 99) with ( patch( "homeassistant.components.esphome.manager.ReconnectLogic", BaseMockReconnectLogic, ), patch("homeassistant.components.esphome.APIClient", mock_client), patch("homeassistant.components.esphome.config_flow.APIClient", mock_client), ): yield mock_client
Mock setting up a config entry.
def mock_setup_entry(): """Mock setting up a config entry.""" with patch("homeassistant.components.esphome.async_setup_entry", return_value=True): yield
Stub reconnect.
def stub_reconnect(): """Stub reconnect.""" with patch("homeassistant.components.esphome.manager.ReconnectLogic.start"): yield
Return the UDP pipeline factory.
def voice_assistant_udp_pipeline( hass: HomeAssistant, ) -> VoiceAssistantUDPPipeline: """Return the UDP pipeline factory.""" def _voice_assistant_udp_server(entry): entry_data = DomainData.get(hass).get_entry_data(entry) server: VoiceAssistantUDPPipeline = None def handle_finished(): nonlocal server assert server is not None server.close() server = VoiceAssistantUDPPipeline(hass, entry_data, Mock(), handle_finished) return server # noqa: RET504 return _voice_assistant_udp_server
Return the API Pipeline factory.
def voice_assistant_api_pipeline( hass: HomeAssistant, mock_client, mock_voice_assistant_api_entry, ) -> VoiceAssistantAPIPipeline: """Return the API Pipeline factory.""" entry_data = DomainData.get(hass).get_entry_data(mock_voice_assistant_api_entry) return VoiceAssistantAPIPipeline(hass, entry_data, Mock(), Mock(), mock_client)
Return the UDP pipeline.
def voice_assistant_udp_pipeline_v1( voice_assistant_udp_pipeline, mock_voice_assistant_v1_entry, ) -> VoiceAssistantUDPPipeline: """Return the UDP pipeline.""" return voice_assistant_udp_pipeline(entry=mock_voice_assistant_v1_entry)
Return the UDP pipeline.
def voice_assistant_udp_pipeline_v2( voice_assistant_udp_pipeline, mock_voice_assistant_v2_entry, ) -> VoiceAssistantUDPPipeline: """Return the UDP pipeline.""" return voice_assistant_udp_pipeline(entry=mock_voice_assistant_v2_entry)
Return one second of empty WAV audio.
def test_wav() -> bytes: """Return one second of empty WAV audio.""" with io.BytesIO() as wav_io: with wave.open(wav_io, "wb") as wav_file: wav_file.setframerate(16000) wav_file.setsampwidth(2) wav_file.setnchannels(1) wav_file.writeframes(bytes(_ONE_SECOND)) return wav_io.getvalue()
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Mock config flow.
def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]: """Mock config flow.""" mock_platform(hass, f"{TEST_DOMAIN}.config_flow") with mock_config_flow(TEST_DOMAIN, MockFlow): yield
Test RGB to integer conversion.
def test_color_rgb_to_int() -> None: """Test RGB to integer conversion.""" assert everlights.color_rgb_to_int(0x00, 0x00, 0x00) == 0x000000 assert everlights.color_rgb_to_int(0xFF, 0xFF, 0xFF) == 0xFFFFFF assert everlights.color_rgb_to_int(0x12, 0x34, 0x56) == 0x123456
Test integer to RGB conversion.
def test_int_to_rgb() -> None: """Test integer to RGB conversion.""" assert everlights.color_int_to_rgb(0x000000) == (0x00, 0x00, 0x00) assert everlights.color_int_to_rgb(0xFFFFFF) == (0xFF, 0xFF, 0xFF) assert everlights.color_int_to_rgb(0x123456) == (0x12, 0x34, 0x56)
Fixture data.
def all_fixture(): """Fixture data.""" data = json.loads(load_fixture("data.json", "evil_genius_labs")) return {item["name"]: item for item in data}