response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Send a notification message.
def send_message(hass, message, title=None, data=None): """Send a notification message.""" info = {ATTR_MESSAGE: message} if title is not None: info[ATTR_TITLE] = title if data is not None: info[ATTR_DATA] = data hass.services.call(DOMAIN, SERVICE_NOTIFY, info)
Mock config flow.
def config_flow_fixture(hass: HomeAssistant) -> Generator[None, None, None]: """Mock config flow.""" mock_platform(hass, "test.config_flow") with mock_config_flow("test", MockFlow): yield
Specialize the mock platform for legacy notify service.
def mock_notify_platform( hass: HomeAssistant, tmp_path: Path, integration: str = "notify", async_get_service: Any = None, get_service: Any = None, ): """Specialize the mock platform for legacy notify service.""" loaded_platform = MockNotifyPlatform(async_get_service, get_service) mock_platform(hass, f"{integration}.notify", loaded_platform) return loaded_platform
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.notion.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Define a fixture for an aionotion client.
def client_fixture(data_bridge, data_listener, data_sensor, data_user_preferences): """Define a fixture for an aionotion client.""" return Mock( bridge=Mock( async_all=AsyncMock( return_value=[ Bridge.from_dict(bridge) for bridge in data_bridge["base_stations"] ] ) ), listener=Mock( async_all=AsyncMock( return_value=[ Listener.from_dict(listener) for listener in data_listener["listeners"] ] ) ), refresh_token=TEST_REFRESH_TOKEN, sensor=Mock( async_all=AsyncMock( return_value=[ Sensor.from_dict(sensor) for sensor in data_sensor["sensors"] ] ) ), user=Mock( async_preferences=AsyncMock( return_value=UserPreferences.from_dict( data_user_preferences["user_preferences"] ) ) ), user_uuid=TEST_USER_UUID, )
Define a config entry fixture.
def config_entry_fixture(hass: HomeAssistant, config): """Define a config entry fixture.""" entry = MockConfigEntry(domain=DOMAIN, unique_id=TEST_USERNAME, 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_USERNAME: TEST_USERNAME, CONF_USER_UUID: TEST_USER_UUID, CONF_REFRESH_TOKEN: TEST_REFRESH_TOKEN, }
Define bridge data.
def data_bridge_fixture(): """Define bridge data.""" return json.loads(load_fixture("bridge_data.json", "notion"))
Define listener data.
def data_listener_fixture(): """Define listener data.""" return json.loads(load_fixture("listener_data.json", "notion"))
Define sensor data.
def data_sensor_fixture(): """Define sensor data.""" return json.loads(load_fixture("sensor_data.json", "notion"))
Define user preferences data.
def data_user_preferences_fixture(): """Define user preferences data.""" return json.loads(load_fixture("user_preferences_data.json", "notion"))
Define a fixture to mock the client retrieval methods.
def get_client_fixture(client): """Define a fixture to mock the client retrieval methods.""" return AsyncMock(return_value=client)
Fixture that sets up NO-IP.
def setup_no_ip(hass, aioclient_mock): """Fixture that sets up NO-IP.""" aioclient_mock.get(UPDATE_URL, params={"hostname": DOMAIN}, text="good 0.0.0.0") hass.loop.run_until_complete( async_setup_component( hass, no_ip.DOMAIN, { no_ip.DOMAIN: { "domain": DOMAIN, "username": USERNAME, "password": PASSWORD, } }, ) )
Raise fuel check error for testing error cases.
def raise_fuel_check_error(): """Raise fuel check error for testing error cases.""" raise FuelCheckError
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, distance_to_home, coordinates, category=None, location=None, attribution=None, publication_date=None, council_area=None, status=None, entry_type=None, fire=True, size=None, responsible_agency=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.category = category feed_entry.location = location feed_entry.attribution = attribution feed_entry.publication_date = publication_date feed_entry.council_area = council_area feed_entry.status = status feed_entry.type = entry_type feed_entry.fire = fire feed_entry.size = size feed_entry.responsible_agency = responsible_agency return feed_entry
Return a default nuheat config.
def _mock_get_config(): """Return a default nuheat config.""" return { DOMAIN: {CONF_USERNAME: "me", CONF_PASSWORD: "secret", CONF_DEVICES: [12345]} }
Mockup to replace regular functions for error injection.
def mockup_raise(*args, **kwargs): """Mockup to replace regular functions for error injection.""" raise NumatoGpioError("Error mockup")
Mockup to replace regular functions for error injection.
def mockup_return(*args, **kwargs): """Mockup to replace regular functions for error injection.""" return False
Provide a copy of the numato domain's test configuration. This helps to quickly change certain aspects of the configuration scoped to each individual test.
def config(): """Provide a copy of the numato domain's test configuration. This helps to quickly change certain aspects of the configuration scoped to each individual test. """ return deepcopy(NUMATO_CFG)
Inject the numato mockup into numato homeassistant module.
def numato_fixture(monkeypatch): """Inject the numato mockup into numato homeassistant module.""" module_mock = numato_mock.NumatoModuleMock() monkeypatch.setattr(numato, "gpio", module_mock) return module_mock
Return a list of mock number entities.
def mock_number_entities() -> list[MockNumberEntity]: """Return a list of mock number entities.""" return [ MockNumberEntity( name="test", unique_id="unique_number", native_value=50.0, ), ]
Test module.__all__ is correctly set.
def test_all() -> None: """Test module.__all__ is correctly set.""" help_test_all(const)
Test deprecated constants.
def test_deprecated_constants( caplog: pytest.LogCaptureFixture, enum: const.NumberMode, ) -> None: """Test deprecated constants.""" import_and_test_deprecated_constant_enum(caplog, const, enum, "MODE_", "2025.1")
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."""
Make sure all sensor device classes are also available in NumberDeviceClass.
def test_device_classes_aligned() -> None: """Make sure all sensor device classes are also available in NumberDeviceClass.""" for device_class in SensorDeviceClass: if device_class in NON_NUMERIC_DEVICE_CLASSES: continue assert hasattr(NumberDeviceClass, device_class.name) assert getattr(NumberDeviceClass, device_class.name).value == device_class.value for device_class in SENSOR_DEVICE_CLASS_UNITS: if device_class in NON_NUMERIC_DEVICE_CLASSES: continue assert ( SENSOR_DEVICE_CLASS_UNITS[device_class] == NUMBER_DEVICE_CLASS_UNITS[device_class] )
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 all numeric device classes have unit.
def test_device_class_units(hass: HomeAssistant) -> None: """Test all numeric device classes have unit.""" # DEVICE_CLASS_UNITS should include all device classes except: # - NumberDeviceClass.MONETARY # - Device classes enumerated in NON_NUMERIC_DEVICE_CLASSES assert set(NUMBER_DEVICE_CLASS_UNITS) == set( NumberDeviceClass ) - NON_NUMERIC_DEVICE_CLASSES - {NumberDeviceClass.MONETARY}
Mock pynws SimpleNWS with default values.
def mock_simple_nws(): """Mock pynws SimpleNWS with default values.""" with patch("homeassistant.components.nws.SimpleNWS") as mock_nws: instance = mock_nws.return_value instance.set_station = AsyncMock(return_value=None) instance.update_observation = AsyncMock(return_value=None) instance.update_forecast = AsyncMock(return_value=None) instance.update_forecast_hourly = AsyncMock(return_value=None) instance.station = "ABC" instance.stations = ["ABC"] instance.observation = DEFAULT_OBSERVATION instance.forecast = DEFAULT_FORECAST instance.forecast_hourly = DEFAULT_FORECAST yield mock_nws
Mock pynws SimpleNWS that times out.
def mock_simple_nws_times_out(): """Mock pynws SimpleNWS that times out.""" with patch("homeassistant.components.nws.SimpleNWS") as mock_nws: instance = mock_nws.return_value instance.set_station = AsyncMock(side_effect=asyncio.TimeoutError) instance.update_observation = AsyncMock(side_effect=asyncio.TimeoutError) instance.update_forecast = AsyncMock(side_effect=asyncio.TimeoutError) instance.update_forecast_hourly = AsyncMock(side_effect=asyncio.TimeoutError) instance.station = "ABC" instance.stations = ["ABC"] instance.observation = None instance.forecast = None instance.forecast_hourly = None yield mock_nws
Mock pynws SimpleNWS with default values in config_flow.
def mock_simple_nws_config(): """Mock pynws SimpleNWS with default values in config_flow.""" with patch("homeassistant.components.nws.config_flow.SimpleNWS") as mock_nws: instance = mock_nws.return_value instance.set_station = AsyncMock(return_value=None) instance.station = "ABC" instance.stations = ["ABC"] yield mock_nws
Remove sensors.
def no_sensor(): """Remove sensors.""" with patch( "homeassistant.components.nws.sensor.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Remove weather.
def no_weather(): """Remove weather.""" with patch( "homeassistant.components.nws.weather.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Fixture for fake zones. Returns: list: List of fake zones
def fake_zones(): """Fixture for fake zones. Returns: list: List of fake zones """ return [ {"name": "front", "number": 1}, {"name": "back", "number": 2}, {"name": "inside", "number": 3}, ]
Fixture for client. Args: fake_zones (list): Fixture of fake zones Yields: MagicMock: Client Mock
def client(fake_zones): """Fixture for client. Args: fake_zones (list): Fixture of fake zones Yields: MagicMock: Client Mock """ with mock.patch.object(nx584_client, "Client") as _mock_client: client = nx584_client.Client.return_value client.list_zones.return_value = fake_zones client.get_version.return_value = "1.1" yield _mock_client
Test the setup with no configuration.
def test_nx584_sensor_setup_defaults( mock_nx, mock_watcher, hass: HomeAssistant, fake_zones ) -> None: """Test the setup with no configuration.""" add_entities = mock.MagicMock() config = DEFAULT_CONFIG nx584.setup_platform(hass, config, add_entities) mock_nx.assert_has_calls([mock.call(zone, "opening") for zone in fake_zones]) assert add_entities.called assert nx584_client.Client.call_count == 1 assert nx584_client.Client.call_args == mock.call("http://localhost:5007")
Test the setup with full configuration.
def test_nx584_sensor_setup_full_config( mock_nx, mock_watcher, hass: HomeAssistant, fake_zones ) -> None: """Test the setup with full configuration.""" config = { "host": "foo", "port": 123, "exclude_zones": [2], "zone_types": {3: "motion"}, } add_entities = mock.MagicMock() nx584.setup_platform(hass, config, add_entities) mock_nx.assert_has_calls( [ mock.call(fake_zones[0], "opening"), mock.call(fake_zones[2], "motion"), ] ) assert add_entities.called assert nx584_client.Client.call_count == 1 assert nx584_client.Client.call_args == mock.call("http://foo:123") assert mock_watcher.called
Test the setup with no zones.
def test_nx584_sensor_setup_no_zones(hass: HomeAssistant) -> None: """Test the setup with no zones.""" nx584_client.Client.return_value.list_zones.return_value = [] add_entities = mock.MagicMock() nx584.setup_platform( hass, DEFAULT_CONFIG, add_entities, ) assert not add_entities.called
Test for the NX584 zone sensor.
def test_nx584_zone_sensor_normal() -> None: """Test for the NX584 zone sensor.""" zone = {"number": 1, "name": "foo", "state": True} sensor = nx584.NX584ZoneSensor(zone, "motion") assert sensor.name == "foo" assert not sensor.should_poll assert sensor.is_on assert sensor.extra_state_attributes["zone_number"] == 1 assert not sensor.extra_state_attributes["bypassed"] zone["state"] = False assert not sensor.is_on
Test for the NX584 zone sensor.
def test_nx584_zone_sensor_bypassed() -> None: """Test for the NX584 zone sensor.""" zone = {"number": 1, "name": "foo", "state": True, "bypassed": True} sensor = nx584.NX584ZoneSensor(zone, "motion") assert sensor.name == "foo" assert not sensor.should_poll assert sensor.is_on assert sensor.extra_state_attributes["zone_number"] == 1 assert sensor.extra_state_attributes["bypassed"] zone["state"] = False zone["bypassed"] = False assert not sensor.is_on assert not sensor.extra_state_attributes["bypassed"]
Test the processing of zone events.
def test_nx584_watcher_process_zone_event(mock_update) -> None: """Test the processing of zone events.""" zone1 = {"number": 1, "name": "foo", "state": True} zone2 = {"number": 2, "name": "bar", "state": True} zones = { 1: nx584.NX584ZoneSensor(zone1, "motion"), 2: nx584.NX584ZoneSensor(zone2, "motion"), } watcher = nx584.NX584Watcher(None, zones) watcher._process_zone_event({"zone": 1, "zone_state": False}) assert not zone1["state"] assert mock_update.call_count == 1
Test the processing of zone events with missing zones.
def test_nx584_watcher_process_zone_event_missing_zone(mock_update) -> None: """Test the processing of zone events with missing zones.""" watcher = nx584.NX584Watcher(None, {}) watcher._process_zone_event({"zone": 1, "zone_state": False}) assert not mock_update.called
Test the zone events.
def test_nx584_watcher_run_with_zone_events() -> None: """Test the zone events.""" empty_me = [1, 2] def fake_get_events(): """Return nothing twice, then some events.""" if empty_me: empty_me.pop() else: return fake_events client = mock.MagicMock() fake_events = [ {"zone": 1, "zone_state": True, "type": "zone_status"}, {"zone": 2, "foo": False}, ] client.get_events.side_effect = fake_get_events watcher = nx584.NX584Watcher(client, {}) @mock.patch.object(watcher, "_process_zone_event") def run(fake_process): """Run a fake process.""" fake_process.side_effect = StopMe with pytest.raises(StopMe): watcher._run() assert fake_process.call_count == 1 assert fake_process.call_args == mock.call(fake_events[0]) run() assert client.get_events.call_count == 3
Test the retries with failures.
def test_nx584_watcher_run_retries_failures(mock_sleep) -> None: """Test the retries with failures.""" empty_me = [1, 2] def fake_run(): """Fake runner.""" if empty_me: empty_me.pop() raise requests.exceptions.ConnectionError raise StopMe watcher = nx584.NX584Watcher(None, {}) with mock.patch.object(watcher, "_run") as mock_inner: mock_inner.side_effect = fake_run with pytest.raises(StopMe): watcher.run() assert mock_inner.call_count == 3 mock_sleep.assert_has_calls([mock.call(10), mock.call(10)])
Mock NZBGetApi for easier testing.
def nzbget_api(hass): """Mock NZBGetApi for easier testing.""" with patch("homeassistant.components.nzbget.coordinator.NZBGetAPI") as mock_api: instance = mock_api.return_value instance.history = MagicMock(return_value=list(MOCK_HISTORY)) instance.pausedownload = MagicMock(return_value=True) instance.resumedownload = MagicMock(return_value=True) instance.status = MagicMock(return_value=MOCK_STATUS.copy()) instance.version = MagicMock(return_value=MOCK_VERSION) yield mock_api
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.obihai.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Override async_setup_entry.
def mock_gaierror() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.obihai.config_flow.gethostbyname", side_effect=gaierror(), ) as mock_setup_entry: yield mock_setup_entry
Get suggested value for key in voluptuous schema.
def get_schema_suggestion(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"]
Mock a config entry.
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry: """Mock a config entry.""" entry = MockConfigEntry( domain=ollama.DOMAIN, data=TEST_USER_DATA, options=TEST_OPTIONS, ) entry.add_to_hass(hass) return entry
Ensure auth is always active.
def auth_active(hass): """Ensure auth is always active.""" hass.loop.run_until_complete( register_auth_provider(hass, {"type": "homeassistant"}) )
Mock the default integrations set up during onboarding.
def mock_default_integrations(): """Mock the default integrations set up during onboarding.""" with ( patch("homeassistant.components.rpi_power.config_flow.new_under_voltage"), patch("homeassistant.components.rpi_power.binary_sensor.new_under_voltage"), patch("homeassistant.components.met.async_setup_entry", return_value=True), patch( "homeassistant.components.radio_browser.async_setup_entry", return_value=True, ), patch( "homeassistant.components.shopping_list.async_setup_entry", return_value=True, ), ): yield
Mock the onboarding storage.
def mock_storage(hass_storage, data): """Mock the onboarding storage.""" hass_storage[onboarding.STORAGE_KEY] = { "version": onboarding.STORAGE_VERSION, "data": data, }
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.onewire.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Parametrize device id.
def get_device_id(request: pytest.FixtureRequest) -> str: """Parametrize device id.""" return request.param
Create and register mock config entry.
def get_config_entry(hass: HomeAssistant) -> ConfigEntry: """Create and register mock config entry.""" config_entry = MockConfigEntry( domain=DOMAIN, source=SOURCE_USER, data={ CONF_HOST: "1.2.3.4", CONF_PORT: 1234, }, options={ "device_options": { "28.222222222222": {"precision": "temperature9"}, "28.222222222223": {"precision": "temperature5"}, } }, entry_id="2", ) config_entry.add_to_hass(hass) return config_entry
Mock owproxy.
def get_owproxy() -> MagicMock: """Mock owproxy.""" with patch("homeassistant.components.onewire.onewirehub.protocol.proxy") as owproxy: yield owproxy
Mock owproxy.
def get_owproxy_with_connerror() -> MagicMock: """Mock owproxy.""" with patch( "homeassistant.components.onewire.onewirehub.protocol.proxy", side_effect=ConnError, ) as owproxy: yield owproxy
Override PLATFORMS.
def override_platforms() -> Generator[None, None, None]: """Override PLATFORMS.""" with patch("homeassistant.components.onewire.PLATFORMS", [Platform.BINARY_SENSOR]): yield
Override PLATFORMS.
def override_platforms() -> Generator[None, None, None]: """Override PLATFORMS.""" with patch("homeassistant.components.onewire.PLATFORMS", [Platform.SWITCH]): yield
Override PLATFORMS.
def override_platforms() -> Generator[None, None, None]: """Override PLATFORMS.""" with patch("homeassistant.components.onewire.PLATFORMS", [Platform.SENSOR]): yield
Override PLATFORMS.
def override_platforms() -> Generator[None, None, None]: """Override PLATFORMS.""" with patch("homeassistant.components.onewire.PLATFORMS", [Platform.SWITCH]): yield
Set up mock for owproxy.
def setup_owproxy_mock_devices( owproxy: MagicMock, platform: Platform, device_ids: list[str] ) -> None: """Set up mock for owproxy.""" main_dir_return_value = [] sub_dir_side_effect = [] main_read_side_effect = [] sub_read_side_effect = [] for device_id in device_ids: _setup_owproxy_mock_device( main_dir_return_value, sub_dir_side_effect, main_read_side_effect, sub_read_side_effect, device_id, platform, ) # Ensure enough read side effect dir_side_effect = [main_dir_return_value, *sub_dir_side_effect] read_side_effect = ( main_read_side_effect + sub_read_side_effect + [ProtocolError("Missing injected value")] * 20 ) owproxy.return_value.dir.side_effect = dir_side_effect owproxy.return_value.read.side_effect = read_side_effect
Set up mock for owproxy.
def _setup_owproxy_mock_device( main_dir_return_value: list, sub_dir_side_effect: list, main_read_side_effect: list, sub_read_side_effect: list, device_id: str, platform: Platform, ) -> None: """Set up mock for owproxy.""" mock_device = MOCK_OWPROXY_DEVICES[device_id] # Setup directory listing main_dir_return_value += [f"/{device_id}/"] if "branches" in mock_device: # Setup branch directory listing for branch, branch_details in mock_device["branches"].items(): sub_dir_side_effect.append( [ # dir on branch f"/{device_id}/{branch}/{sub_device_id}/" for sub_device_id in branch_details ] ) _setup_owproxy_mock_device_reads( main_read_side_effect, sub_read_side_effect, mock_device, device_id, platform, ) if "branches" in mock_device: for branch_details in mock_device["branches"].values(): for sub_device_id, sub_device in branch_details.items(): _setup_owproxy_mock_device_reads( main_read_side_effect, sub_read_side_effect, sub_device, sub_device_id, platform, )
Set up mock for owproxy.
def _setup_owproxy_mock_device_reads( main_read_side_effect: list, sub_read_side_effect: list, mock_device: Any, device_id: str, platform: Platform, ) -> None: """Set up mock for owproxy.""" # Setup device reads main_read_side_effect += [device_id[0:2].encode()] if ATTR_INJECT_READS in mock_device: main_read_side_effect += mock_device[ATTR_INJECT_READS] # Setup sub-device reads device_sensors = mock_device.get(platform, []) if platform is Platform.SENSOR and device_id.startswith("12"): # We need to check if there is TAI8570 plugged in sub_read_side_effect.extend( expected_sensor[ATTR_INJECT_READS] for expected_sensor in device_sensors ) sub_read_side_effect.extend( expected_sensor[ATTR_INJECT_READS] for expected_sensor in device_sensors )
Prepare mock discovery result.
def setup_mock_discovery( mock_discovery, with_name=False, with_mac=False, two_devices=False, with_hardware=True, no_devices=False, ): """Prepare mock discovery result.""" services = [] for item in DISCOVERY: if no_devices: continue service = MagicMock() service.getXAddrs = MagicMock( return_value=[ f"http://{item[config_flow.CONF_HOST]}:{item[config_flow.CONF_PORT]}/onvif/device_service" ] ) service.getEPR = MagicMock(return_value=item["EPR"]) scopes = [] if with_name: scope = MagicMock() scope.getValue = MagicMock( return_value=f"onvif://www.onvif.org/name/{item[config_flow.CONF_NAME]}" ) scopes.append(scope) if with_mac: scope = MagicMock() scope.getValue = MagicMock( return_value=f"onvif://www.onvif.org/mac/{item['MAC']}" ) scopes.append(scope) if with_hardware and "HARDWARE" in item: scope = MagicMock() scope.getValue = MagicMock( return_value=f"onvif://www.onvif.org/hardware/{item['HARDWARE']}" ) scopes.append(scope) service.getScopes = MagicMock(return_value=scopes) services.append(service) mock_ws_discovery = MagicMock() mock_ws_discovery.searchServices = MagicMock(return_value=services) mock_discovery.return_value = mock_ws_discovery
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")
Prepare mock onvif.ONVIFCamera.
def setup_mock_onvif_camera( mock_onvif_camera, with_h264=True, two_profiles=False, with_interfaces=True, with_interfaces_not_implemented=False, with_serial=True, profiles_transient_failure=False, auth_fail=False, update_xaddrs_fail=False, no_profiles=False, auth_failure=False, wrong_port=False, ): """Prepare mock onvif.ONVIFCamera.""" devicemgmt = MagicMock() device_info = MagicMock() device_info.SerialNumber = SERIAL_NUMBER if with_serial else None devicemgmt.GetDeviceInformation = AsyncMock(return_value=device_info) interface = MagicMock() interface.Enabled = True interface.Info.HwAddress = MAC if with_interfaces_not_implemented: devicemgmt.GetNetworkInterfaces = AsyncMock( side_effect=Fault("not implemented") ) else: devicemgmt.GetNetworkInterfaces = AsyncMock( return_value=[interface] if with_interfaces else [] ) media_service = MagicMock() profile1 = MagicMock() profile1.VideoEncoderConfiguration.Encoding = "H264" if with_h264 else "MJPEG" profile2 = MagicMock() profile2.VideoEncoderConfiguration.Encoding = "H264" if two_profiles else "MJPEG" if auth_fail: media_service.GetProfiles = AsyncMock(side_effect=Fault("Authority failure")) elif profiles_transient_failure: media_service.GetProfiles = AsyncMock(side_effect=Fault("camera not ready")) elif no_profiles: media_service.GetProfiles = AsyncMock(return_value=[]) else: media_service.GetProfiles = AsyncMock(return_value=[profile1, profile2]) if wrong_port: mock_onvif_camera.update_xaddrs = AsyncMock(side_effect=AttributeError) elif auth_failure: mock_onvif_camera.update_xaddrs = AsyncMock( side_effect=Fault( "not authorized", subcodes=[MagicMock(text="NotAuthorized")] ) ) elif update_xaddrs_fail: mock_onvif_camera.update_xaddrs = AsyncMock( side_effect=ONVIFError("camera not ready") ) else: mock_onvif_camera.update_xaddrs = AsyncMock(return_value=True) mock_onvif_camera.create_devicemgmt_service = AsyncMock(return_value=devicemgmt) mock_onvif_camera.create_media_service = AsyncMock(return_value=media_service) mock_onvif_camera.close = AsyncMock(return_value=None) mock_onvif_camera.xaddrs = {} mock_onvif_camera.services = {} def mock_constructor( host, port, user, passwd, wsdl_dir, encrypt=True, no_cache=False, adjust_time=False, transport=None, ): """Fake the controller constructor.""" return mock_onvif_camera mock_onvif_camera.side_effect = mock_constructor
Prepare mock ONVIFDevice.
def setup_mock_device(mock_device, capabilities=None): """Prepare mock ONVIFDevice.""" mock_device.async_setup = AsyncMock(return_value=True) mock_device.port = 80 mock_device.available = True mock_device.name = NAME mock_device.info = DeviceInfo( MANUFACTURER, MODEL, FIRMWARE_VERSION, SERIAL_NUMBER, MAC, ) mock_device.capabilities = capabilities or Capabilities(imaging=True, ptz=True) profile1 = Profile( index=0, token="dummy", name="profile1", video=Video("any", Resolution(640, 480)), ptz=None, video_source_token=None, ) mock_device.profiles = [profile1] mock_device.events = MagicMock( webhook_manager=MagicMock(state=WebHookManagerState.STARTED), pullpoint_manager=MagicMock(state=PullPointManagerState.PAUSED), ) def mock_constructor(hass, config): """Fake the controller constructor.""" return mock_device mock_device.side_effect = mock_constructor
Mock a config entry.
def mock_config_entry(hass): """Mock a config entry.""" entry = MockConfigEntry( title="OpenAI", domain="openai_conversation", data={ "api_key": "bla", }, ) entry.add_to_hass(hass) return entry
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( domain=DOMAIN, data={"api_key": "test-api-key", "base": "USD"} )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.openexchangerates.async_setup_entry", return_value=True, ) as mock_setup: yield mock_setup
Return a mocked WLED client.
def mock_latest_rates_config_flow( request: pytest.FixtureRequest, ) -> Generator[AsyncMock, None, None]: """Return a mocked WLED client.""" with patch( "homeassistant.components.openexchangerates.config_flow.Client.get_latest", ) as mock_latest: mock_latest.return_value = {"EUR": 1.0} yield mock_latest
Mock currencies.
def currencies_fixture(hass: HomeAssistant) -> Generator[AsyncMock, None, None]: """Mock currencies.""" with patch( "homeassistant.components.openexchangerates.config_flow.Client.get_currencies", return_value={"USD": "United States Dollar", "EUR": "Euro"}, ) as mock_currencies: yield mock_currencies
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="Test device", domain=DOMAIN, data={ CONF_HOST: "http://1.1.1.1", CONF_PORT: "80", CONF_DEVICE_KEY: "abc123", CONF_VERIFY_SSL: False, }, unique_id="12345", )
Return a mocked OpenGarage client.
def mock_opengarage() -> Generator[MagicMock, None, None]: """Return a mocked OpenGarage client.""" with patch( "homeassistant.components.opengarage.opengarage.OpenGarage", autospec=True, ) as client_mock: client = client_mock.return_value client.device_url = "http://1.1.1.1:80" client.update_state.return_value = { "name": "abcdef", "mac": "aa:bb:cc:dd:ee:ff", "fwv": "1.2.0", } yield client
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.opensky.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Create OpenSky entry in Home Assistant.
def mock_config_entry() -> MockConfigEntry: """Create OpenSky entry in Home Assistant.""" return MockConfigEntry( domain=DOMAIN, title="OpenSky", data={ CONF_LATITUDE: 0.0, CONF_LONGITUDE: 0.0, }, options={ CONF_RADIUS: 10.0, CONF_ALTITUDE: 0.0, }, )
Create Opensky entry with altitude in Home Assistant.
def mock_config_entry_altitude() -> MockConfigEntry: """Create Opensky entry with altitude in Home Assistant.""" return MockConfigEntry( domain=DOMAIN, title="OpenSky", data={ CONF_LATITUDE: 0.0, CONF_LONGITUDE: 0.0, }, options={ CONF_RADIUS: 10.0, CONF_ALTITUDE: 12500.0, }, )
Create authenticated Opensky entry in Home Assistant.
def mock_config_entry_authenticated() -> MockConfigEntry: """Create authenticated Opensky entry in Home Assistant.""" return MockConfigEntry( domain=DOMAIN, title="OpenSky", data={ CONF_LATITUDE: 0.0, CONF_LONGITUDE: 0.0, }, options={ CONF_RADIUS: 10.0, CONF_ALTITUDE: 12500.0, CONF_USERNAME: "asd", CONF_PASSWORD: "secret", CONF_CONTRIBUTING_USER: True, }, )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.openuv.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Define a mock Client object.
def client_fixture(data_protection_window, data_uv_index): """Define a mock Client object.""" return Mock( uv_index=AsyncMock(return_value=data_uv_index), uv_protection_window=AsyncMock(return_value=data_protection_window), )
Define a config entry fixture.
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=f"{config[CONF_LATITUDE]}, {config[CONF_LONGITUDE]}", data=config, options={CONF_FROM_WINDOW: 3.5, CONF_TO_WINDOW: 3.5}, ) entry.add_to_hass(hass) return entry
Define a config entry data fixture.
def config_fixture(): """Define a config entry data fixture.""" return { CONF_API_KEY: TEST_API_KEY, CONF_ELEVATION: TEST_ELEVATION, CONF_LATITUDE: TEST_LATITUDE, CONF_LONGITUDE: TEST_LONGITUDE, }
Define a fixture to return UV protection window data.
def data_protection_window_fixture(): """Define a fixture to return UV protection window data.""" return json.loads(load_fixture("protection_window_data.json", "openuv"))
Define a fixture to return UV index data.
def data_uv_index_fixture(): """Define a fixture to return UV index data.""" return json.loads(load_fixture("uv_index_data.json", "openuv"))
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="Home", domain=DOMAIN, data={CONF_ZONE: "zone.home"}, unique_id="zone.home", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.open_meteo.async_setup_entry", return_value=True ): yield
Return a mocked Open-Meteo client.
def mock_open_meteo(request: pytest.FixtureRequest) -> Generator[None, MagicMock, None]: """Return a mocked Open-Meteo client.""" fixture: str = "forecast.json" if hasattr(request, "param") and request.param: fixture = request.param forecast = Forecast.from_json(load_fixture(fixture, DOMAIN)) with patch( "homeassistant.components.open_meteo.OpenMeteo", autospec=True ) as open_meteo_mock: open_meteo = open_meteo_mock.return_value open_meteo.forecast.return_value = forecast yield open_meteo
Mock for pyopnense.diagnostics.
def mocked_opnsense(): """Mock for pyopnense.diagnostics.""" with mock.patch.object(opnsense, "diagnostics") as mocked_opn: yield mocked_opn
Return the default mocked config entry.
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry: """Return the default mocked config entry.""" config_entry = MockConfigEntry( title="Pacific Gas & Electric (test-username)", domain=DOMAIN, data={ "utility": "Pacific Gas and Electric Company (PG&E)", "username": "test-username", "password": "test-password", }, ) config_entry.add_to_hass(hass) return config_entry
Override async_setup_entry.
def override_async_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.opower.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock unloading a config entry.
def mock_unload_entry() -> Generator[AsyncMock, None, None]: """Mock unloading a config entry.""" with patch( "homeassistant.components.opower.async_unload_entry", return_value=True, ) as mock_unload_entry: yield mock_unload_entry
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth.""" with mock.patch( "oralb_ble.parser.BleakClientWithServiceCache", MockBleakClientBattery49 ): yield
Mock zeroconf in all tests.
def use_mocked_zeroconf(mock_async_zeroconf): """Mock zeroconf in all tests."""
Mock the Silicon Labs Multiprotocol add-on manager.
def multiprotocol_addon_manager_mock_fixture(hass: HomeAssistant): """Mock the Silicon Labs Multiprotocol add-on manager.""" mock_manager = Mock() mock_manager.async_get_channel = Mock(return_value=None) with patch.dict(hass.data, {"silabs_multiprotocol_addon_manager": mock_manager}): yield mock_manager
Mock Supervisor add-on info.
def addon_info_fixture(): """Mock Supervisor add-on info.""" with patch( "homeassistant.components.otbr.config_flow.async_get_addon_info", ) as addon_info: addon_info.return_value = { "available": True, "hostname": None, "options": {}, "state": None, "update_available": False, "version": None, } yield addon_info
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.ourgroceries.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock ourgroceries configuration.
def mock_ourgroceries_config_entry() -> MockConfigEntry: """Mock ourgroceries configuration.""" return MockConfigEntry( domain=DOMAIN, data={CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD} )
Mock a collection of shopping list items.
def mock_items() -> dict: """Mock a collection of shopping list items.""" return []
Mock the OurGroceries api.
def mock_ourgroceries(items: list[dict]) -> AsyncMock: """Mock the OurGroceries api.""" og = AsyncMock() og.login.return_value = True og.get_my_lists.return_value = { "shoppingLists": [{"id": "test_list", "name": "Test List", "versionId": "1"}] } og.get_list_items.return_value = items_to_shopping_list(items) return og
Fixture to simulate error on login.
def login_with_error(exception, ourgroceries: AsyncMock): """Fixture to simulate error on login.""" ourgroceries.login.side_effect = (exception,)