response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Create device registry devices so the device tracker entities are enabled.
def mock_device_registry_devices( hass: HomeAssistant, device_registry: dr.DeviceRegistry ): """Create device registry devices so the device tracker entities are enabled.""" config_entry = MockConfigEntry(domain="something_else") config_entry.add_to_hass(hass) for idx, device in enumerate( ( "68:A3:78:00:00:00", "8C:97:EA:00:00:00", "DE:00:B0:00:00:00", "DC:00:B0:00:00:00", "5E:65:55:00:00:00", ) ): device_registry.async_get_or_create( name=f"Device {idx}", config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, device)}, )
Mock a successful connection.
def mock_router(mock_device_registry_devices): """Mock a successful connection.""" with patch("homeassistant.components.freebox.router.Freepybox") as service_mock: instance = service_mock.return_value instance.open = AsyncMock() instance.system.get_config = AsyncMock(return_value=DATA_SYSTEM_GET_CONFIG) # device_tracker instance.lan.get_hosts_list = AsyncMock(return_value=DATA_LAN_GET_HOSTS_LIST) # sensor instance.call.get_calls_log = AsyncMock(return_value=DATA_CALL_GET_CALLS_LOG) instance.storage.get_disks = AsyncMock(return_value=DATA_STORAGE_GET_DISKS) instance.storage.get_raids = AsyncMock(return_value=DATA_STORAGE_GET_RAIDS) instance.connection.get_status = AsyncMock( return_value=DATA_CONNECTION_GET_STATUS ) # switch instance.wifi.get_global_config = AsyncMock( return_value=DATA_WIFI_GET_GLOBAL_CONFIG ) # home devices instance.home.get_home_nodes = AsyncMock(return_value=DATA_HOME_GET_NODES) instance.home.get_home_endpoint_value = AsyncMock( return_value=DATA_HOME_PIR_GET_VALUE ) instance.home.set_home_endpoint_value = AsyncMock( return_value=DATA_HOME_SET_VALUE ) instance.close = AsyncMock() yield service_mock
Mock a successful connection to Freebox Bridge mode.
def mock_router_bridge_mode(mock_device_registry_devices, router): """Mock a successful connection to Freebox Bridge mode.""" router().lan.get_hosts_list = AsyncMock( side_effect=HttpRequestError( f"Request failed (APIResponse: {json.dumps(DATA_LAN_GET_HOSTS_LIST_MODE_BRIDGE)})" ) ) return router
Mock a failed connection to Freebox Bridge mode.
def mock_router_bridge_mode_error(mock_device_registry_devices, router): """Mock a failed connection to Freebox Bridge mode.""" router().lan.get_hosts_list = AsyncMock( side_effect=HttpRequestError("Request failed (APIResponse: some unknown error)") ) return router
Fixture that sets up FreeDNS.
def setup_freedns(hass, aioclient_mock): """Fixture that sets up FreeDNS.""" params = {} params[ACCESS_TOKEN] = "" aioclient_mock.get( UPDATE_URL, params=params, text="Successfully updated 1 domains." ) hass.loop.run_until_complete( async_setup_component( hass, freedns.DOMAIN, { freedns.DOMAIN: { "access_token": ACCESS_TOKEN, "scan_interval": UPDATE_INTERVAL, } }, ) )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.freedompro.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock freedompro get_list and get_states.
def mock_freedompro(): """Mock freedompro get_list and get_states.""" with ( patch( "homeassistant.components.freedompro.coordinator.get_list", return_value={ "state": True, "devices": DEVICES, }, ), patch( "homeassistant.components.freedompro.coordinator.get_states", return_value=DEVICES_STATE, ), ): yield
Return a deepcopy of the device state list for specific uid.
def get_states_response_for_uid(uid: str) -> list[dict[str, Any]]: """Return a deepcopy of the device state list for specific uid.""" return deepcopy([resp for resp in DEVICES_STATE if resp["uid"] == uid])
Mock freedompro put_state.
def mock_freedompro_put_state(): """Mock freedompro put_state.""" with patch("homeassistant.components.freedompro.light.put_state"): yield
Fixture for default fc_data.
def fc_data_mock(): """Fixture for default fc_data.""" return MOCK_FB_SERVICES
Fixture that sets up a mocked FritzConnection class.
def fc_class_mock(fc_data): """Fixture that sets up a mocked FritzConnection class.""" with patch( "homeassistant.components.fritz.common.FritzConnection", autospec=True ) as result: result.return_value = FritzConnectionMock(fc_data) yield result
Fixture that sets up a mocked FritzHosts class.
def fh_class_mock(): """Fixture that sets up a mocked FritzHosts class.""" with patch( "homeassistant.components.fritz.common.FritzHosts", new=FritzHosts, ) as result: result.get_mesh_topology = MagicMock(return_value=MOCK_MESH_DATA) result.get_hosts_attributes = MagicMock(return_value=MOCK_HOST_ATTRIBUTES_DATA) yield result
Patch libraries.
def fritz_fixture() -> Mock: """Patch libraries.""" with ( patch("homeassistant.components.fritzbox.Fritzhome") as fritz, patch("homeassistant.components.fritzbox.config_flow.Fritzhome"), ): fritz.return_value.get_prefixed_host.return_value = "http://1.2.3.4" yield fritz
Patch libraries.
def fritz_fixture() -> Mock: """Patch libraries.""" with ( patch("homeassistant.components.fritzbox.async_setup_entry"), patch("homeassistant.components.fritzbox.config_flow.Fritzhome") as fritz, ): yield fritz
Set list of devices or templates.
def set_devices( fritz: Mock, devices: list[Mock] | None = None, templates: list[Mock] | None = None ) -> None: """Set list of devices or templates.""" if devices is not None: fritz().get_devices.return_value = devices if templates is not None: fritz().get_templates.return_value = templates
Disable setting up the whole integration in config_flow tests.
def no_setup(): """Disable setting up the whole integration in config_flow tests.""" with patch( "homeassistant.components.fronius.async_setup_entry", return_value=True, ): yield
Return a fixture loader that patches values at nested keys for a given filename.
def _load_and_patch_fixture( override_data: dict[str, list[tuple[list[str], Any]]], ) -> Callable[[str, str | None], str]: """Return a fixture loader that patches values at nested keys for a given filename.""" def load_and_patch(filename: str, integration: str): """Load a fixture and patch given values.""" text = load_fixture(filename, integration) if filename not in override_data: return text _loaded = json.loads(text) for keys, value in override_data[filename]: _dic = _loaded for key in keys[:-1]: _dic = _dic[key] _dic[keys[-1]] = value return json.dumps(_loaded) return load_and_patch
Mock responses for Fronius devices.
def mock_responses( aioclient_mock: AiohttpClientMocker, host: str = MOCK_HOST, fixture_set: str = "symo", inverter_ids: list[str | int] = [1], night: bool = False, override_data: dict[str, list[tuple[list[str], Any]]] | None = None, # {filename: [([list of nested keys], patch_value)]} ) -> None: """Mock responses for Fronius devices.""" aioclient_mock.clear_requests() _night = "_night" if night else "" _load = _load_and_patch_fixture(override_data) if override_data else load_fixture aioclient_mock.get( f"{host}/solar_api/GetAPIVersion.cgi", text=_load(f"{fixture_set}/GetAPIVersion.json", "fronius"), ) for inverter_id in inverter_ids: aioclient_mock.get( f"{host}/solar_api/v1/GetInverterRealtimeData.cgi?Scope=Device&" f"DeviceId={inverter_id}&DataCollection=CommonInverterData", text=_load( f"{fixture_set}/GetInverterRealtimeData_Device_{inverter_id}{_night}.json", "fronius", ), ) aioclient_mock.get( f"{host}/solar_api/v1/GetInverterInfo.cgi", text=_load(f"{fixture_set}/GetInverterInfo{_night}.json", "fronius"), ) aioclient_mock.get( f"{host}/solar_api/v1/GetLoggerInfo.cgi", text=_load(f"{fixture_set}/GetLoggerInfo.json", "fronius"), ) aioclient_mock.get( f"{host}/solar_api/v1/GetMeterRealtimeData.cgi?Scope=System", text=_load(f"{fixture_set}/GetMeterRealtimeData.json", "fronius"), ) aioclient_mock.get( f"{host}/solar_api/v1/GetPowerFlowRealtimeData.fcgi", text=_load(f"{fixture_set}/GetPowerFlowRealtimeData{_night}.json", "fronius"), ) aioclient_mock.get( f"{host}/solar_api/v1/GetStorageRealtimeData.cgi?Scope=System", text=_load(f"{fixture_set}/GetStorageRealtimeData.json", "fronius"), ) aioclient_mock.get( f"{host}/solar_api/v1/GetOhmPilotRealtimeData.cgi?Scope=System", text=_load(f"{fixture_set}/GetOhmPilotRealtimeData.json", "fronius"), )
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
Mock that we're onboarded.
def mock_onboarded(): """Mock that we're onboarded.""" with patch( "homeassistant.components.onboarding.async_is_onboarded", return_value=True ): yield
Fixture to setup the frontend.
def setup_frontend(hass): """Fixture to setup the frontend.""" hass.loop.run_until_complete(async_setup_component(hass, "frontend", {}))
Create a mock Frontier Silicon config entry.
def config_entry() -> MockConfigEntry: """Create a mock Frontier Silicon config entry.""" return MockConfigEntry( domain=DOMAIN, unique_id="mock_radio_id", data={CONF_WEBFSAPI_URL: "http://1.1.1.1:80/webfsapi", CONF_PIN: "1234"}, )
Return a valid webfsapi endpoint.
def mock_valid_device_url() -> Generator[None, None, None]: """Return a valid webfsapi endpoint.""" with patch( "afsapi.AFSAPI.get_webfsapi_endpoint", return_value="http://1.1.1.1:80/webfsapi", ): yield
Make get_friendly_name return a value, indicating a valid pin.
def mock_valid_pin() -> Generator[None, None, None]: """Make get_friendly_name return a value, indicating a valid pin.""" with patch( "afsapi.AFSAPI.get_friendly_name", return_value="Name of the device", ): yield
Return a valid radio_id.
def mock_radio_id() -> Generator[None, None, None]: """Return a valid radio_id.""" with patch("afsapi.AFSAPI.get_radio_id", return_value="mock_radio_id"): yield
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.frontier_silicon.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="Test device", domain=DOMAIN, data={ CONF_HOST: "127.0.0.1", CONF_PASSWORD: "mocked-password", CONF_MAC: "aa:bb:cc:dd:ee:ff", CONF_SSL: False, CONF_VERIFY_SSL: False, }, unique_id="12345", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.fully_kiosk.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Return a mocked Fully Kiosk client for the config flow.
def mock_fully_kiosk_config_flow() -> Generator[MagicMock, None, None]: """Return a mocked Fully Kiosk client for the config flow.""" with patch( "homeassistant.components.fully_kiosk.config_flow.FullyKiosk", autospec=True, ) as client_mock: client = client_mock.return_value client.getDeviceInfo.return_value = { "deviceName": "Test device", "deviceID": "12345", "Mac": "AA:BB:CC:DD:EE:FF", } yield client
Return a mocked Fully Kiosk client.
def mock_fully_kiosk() -> Generator[MagicMock, None, None]: """Return a mocked Fully Kiosk client.""" with patch( "homeassistant.components.fully_kiosk.coordinator.FullyKiosk", autospec=True, ) as client_mock: client = client_mock.return_value client.getDeviceInfo.return_value = json.loads( load_fixture("deviceinfo.json", DOMAIN) ) client.getSettings.return_value = json.loads( load_fixture("listsettings.json", DOMAIN) ) yield client
Set the value of a number entity.
def set_value(hass, entity_id, value): """Set the value of a number entity.""" return hass.services.async_call( number.DOMAIN, "set_value", {ATTR_ENTITY_ID: entity_id, number.ATTR_VALUE: value}, blocking=True, )
Check if MQTT topic has subscription.
def has_subscribed(mqtt_mock: MqttMockHAClient, topic: str) -> bool: """Check if MQTT topic has subscription.""" for call in mqtt_mock.async_subscribe.call_args_list: if call.args[0] == topic: return True return False
Call any service on entity.
def call_service(hass, service, entity_id): """Call any service on entity.""" return hass.services.async_call( switch.DOMAIN, service, {ATTR_ENTITY_ID: entity_id}, blocking=True )
Build a fixture for the Fyta API that connects successfully and returns one device.
def mock_fyta(): """Build a fixture for the Fyta API that connects successfully and returns one device.""" mock_fyta_api = AsyncMock() with patch( "homeassistant.components.fyta.config_flow.FytaConnector", return_value=mock_fyta_api, ) as mock_fyta_api: mock_fyta_api.return_value.login.return_value = {} yield mock_fyta_api
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.fyta.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock garages_amsterdam garages.
def mock_cases(): """Mock garages_amsterdam garages.""" with patch( "odp_amsterdam.ODPAmsterdam.all_garages", return_value=[ Mock( garage_name="IJDok", free_space_short=100, free_space_long=10, short_capacity=120, long_capacity=60, state="ok", ), Mock( garage_name="Arena", free_space_short=200, free_space_long=20, short_capacity=240, long_capacity=80, state="error", ), ], ) as mock_get_garages: yield mock_get_garages
Create hass config fixture.
def mock_entry(): """Create hass config fixture.""" return MockConfigEntry( domain=DOMAIN, data={CONF_ADDRESS: WATER_TIMER_SERVICE_INFO.address} )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.gardena_bluetooth.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Mock data on device.
def mock_read_char_raw(): """Mock data on device.""" return { DeviceInformation.firmware_version.uuid: b"1.2.3", DeviceInformation.model_number.uuid: b"Mock Model", }
Auto mock bluetooth.
def mock_client( enable_bluetooth: None, scan_step, mock_read_char_raw: dict[str, Any] ) -> None: """Auto mock bluetooth.""" client = Mock(spec_set=Client) SENTINEL = object() def _read_char(char: Characteristic, default: Any = SENTINEL): try: return char.decode(mock_read_char_raw[char.uuid]) except KeyError: if default is SENTINEL: raise CharacteristicNotFound from KeyError return default def _read_char_raw(uuid: str, default: Any = SENTINEL): try: val = mock_read_char_raw[uuid] if isinstance(val, Exception): raise val except KeyError: if default is SENTINEL: raise CharacteristicNotFound from KeyError return default return val def _all_char(): return set(mock_read_char_raw.keys()) client.read_char.side_effect = _read_char client.read_char_raw.side_effect = _read_char_raw client.get_all_characteristics_uuid.side_effect = _all_char with ( patch( "homeassistant.components.gardena_bluetooth.config_flow.Client", return_value=client, ), patch("homeassistant.components.gardena_bluetooth.Client", return_value=client), ): yield client
Make sure all entities are enabled.
def enable_all_entities(): """Make sure all entities are enabled.""" with patch( "homeassistant.components.gardena_bluetooth.coordinator.GardenaBluetoothEntity.entity_registry_enabled_default", new=Mock(return_value=True), ): yield
Mock data on device.
def mock_switch_chars(mock_read_char_raw): """Mock data on device.""" mock_read_char_raw[Reset.factory_reset.uuid] = b"\x00" return mock_read_char_raw
Mock data on device.
def mock_switch_chars(mock_read_char_raw): """Mock data on device.""" mock_read_char_raw[Valve.state.uuid] = b"\x00" mock_read_char_raw[Valve.remaining_open_time.uuid] = ( Valve.remaining_open_time.encode(0) ) mock_read_char_raw[Valve.manual_watering_time.uuid] = ( Valve.manual_watering_time.encode(1000) ) return mock_read_char_raw
Create a mock GDACS config entry.
def config_entry() -> MockConfigEntry: """Create a mock GDACS config entry.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_LATITUDE: -41.2, CONF_LONGITUDE: 174.7, CONF_RADIUS: 25, CONF_UNIT_SYSTEM: "metric", CONF_SCAN_INTERVAL: 300.0, CONF_CATEGORIES: [], }, title="-41.2, 174.7", unique_id="-41.2, 174.7", )
Mock gdacs entry setup.
def gdacs_setup_fixture(): """Mock gdacs entry setup.""" with patch("homeassistant.components.gdacs.async_setup_entry", return_value=True): yield
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, distance_to_home, coordinates, attribution=None, alert_level=None, country=None, duration_in_week=None, event_name=None, event_type_short=None, event_type=None, from_date=None, to_date=None, population=None, severity=None, vulnerability=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.attribution = attribution feed_entry.alert_level = alert_level feed_entry.country = country feed_entry.duration_in_week = duration_in_week feed_entry.event_name = event_name feed_entry.event_type_short = event_type_short feed_entry.event_type = event_type feed_entry.from_date = from_date feed_entry.to_date = to_date feed_entry.population = population feed_entry.severity = severity feed_entry.vulnerability = vulnerability return feed_entry
Fake image in RAM for testing.
def fakeimgbytes_png(): """Fake image in RAM for testing.""" buf = BytesIO() Image.new("RGB", (1, 1)).save(buf, format="PNG") return bytes(buf.getbuffer())
Fake image in RAM for testing.
def fakeimgbytes_jpg(): """Fake image in RAM for testing.""" buf = BytesIO() # fake image in ram for testing. Image.new("RGB", (1, 1)).save(buf, format="jpeg") return bytes(buf.getbuffer())
Fake image in RAM for testing.
def fakeimgbytes_svg(): """Fake image in RAM for testing.""" return bytes( '<svg xmlns="http://www.w3.org/2000/svg"><circle r="50"/></svg>', encoding="utf-8", )
Fake image in RAM for testing.
def fakeimgbytes_gif(): """Fake image in RAM for testing.""" buf = BytesIO() # fake image in ram for testing. Image.new("RGB", (1, 1)).save(buf, format="gif") return bytes(buf.getbuffer())
Set up respx to respond to test url with fake image bytes.
def fakeimg_png(fakeimgbytes_png): """Set up respx to respond to test url with fake image bytes.""" respx.get("http://127.0.0.1/testurl/1").respond(stream=fakeimgbytes_png)
Set up respx to respond to test url with fake image bytes.
def fakeimg_gif(fakeimgbytes_gif): """Set up respx to respond to test url with fake image bytes.""" respx.get("http://127.0.0.1/testurl/1").respond(stream=fakeimgbytes_gif)
Mock create stream.
def mock_create_stream(): """Mock create stream.""" mock_stream = Mock() mock_provider = Mock() mock_provider.part_recv = AsyncMock() mock_provider.part_recv.return_value = True mock_stream.add_provider.return_value = mock_provider mock_stream.start = AsyncMock() mock_stream.stop = AsyncMock() return patch( "homeassistant.components.generic.config_flow.create_stream", return_value=mock_stream, )
Define a config entry fixture.
def config_entry_fixture(hass): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, title="Test Camera", unique_id="abc123", data={}, options={ "still_image_url": "http://joebloggs:[email protected]/secret1/file.jpg?pw=qwerty", "stream_source": "http://janebloggs:[email protected]/stream", "username": "johnbloggs", "password": "letmein123", "limit_refetch_to_url_change": False, "authentication": "basic", "framerate": 2.0, "verify_ssl": True, "content_type": "image/jpeg", }, version=1, ) entry.add_to_hass(hass) return entry
Test url redaction.
def test_redact_url(url_in, url_out_expected) -> None: """Test url redaction.""" url_out = redact_url(url_in) assert url_out == url_out_expected
Set up the test sensor.
def _setup_sensor(hass, humidity): """Set up the test sensor.""" hass.states.async_set(ENT_SENSOR, humidity)
Set up the test sensor.
def _setup_sensor(hass, temp): """Set up the test sensor.""" hass.states.async_set(ENT_SENSOR, temp)
Set up the test switch.
def _setup_switch(hass, is_on): """Set up the test switch.""" hass.states.async_set(ENT_SWITCH, STATE_ON if is_on else STATE_OFF) calls = [] @callback def log_call(call): """Log service calls.""" calls.append(call) hass.services.async_register(ha.DOMAIN, SERVICE_TURN_ON, log_call) hass.services.async_register(ha.DOMAIN, SERVICE_TURN_OFF, log_call) return calls
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="1234AB 1", domain=DOMAIN, data={ "id": "mock_user", "auth_implementation": DOMAIN, }, unique_id="mock_user", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.geocaching.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Return a mocked Geocaching API client.
def mock_geocaching_config_flow() -> Generator[None, MagicMock, None]: """Return a mocked Geocaching API client.""" mock_status = GeocachingStatus() mock_status.user.username = "mock_user" with patch( "homeassistant.components.geocaching.config_flow.GeocachingApi", autospec=True ) as geocaching_mock: geocachingapi = geocaching_mock.return_value geocachingapi.update.return_value = mock_status yield geocachingapi
Mock device tracker config loading.
def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading."""
Create a mock GeoNet NZ Quakes config entry.
def config_entry(): """Create a mock GeoNet NZ Quakes config entry.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_LATITUDE: -41.2, CONF_LONGITUDE: 174.7, CONF_RADIUS: 25, CONF_UNIT_SYSTEM: "metric", CONF_SCAN_INTERVAL: 300.0, CONF_MMI: 4, CONF_MINIMUM_MAGNITUDE: 0.0, }, title="-41.2, 174.7", unique_id="-41.2, 174.7", )
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, distance_to_home, coordinates, attribution=None, depth=None, magnitude=None, mmi=None, locality=None, quality=None, time=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.attribution = attribution feed_entry.depth = depth feed_entry.magnitude = magnitude feed_entry.mmi = mmi feed_entry.locality = locality feed_entry.quality = quality feed_entry.time = time return feed_entry
Create a mock GeoNet NZ Volcano config entry.
def config_entry(): """Create a mock GeoNet NZ Volcano config entry.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_LATITUDE: -41.2, CONF_LONGITUDE: 174.7, CONF_RADIUS: 25, CONF_UNIT_SYSTEM: "metric", CONF_SCAN_INTERVAL: 300.0, }, title="-41.2, 174.7", )
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, alert_level, distance_to_home, coordinates, attribution=None, activity=None, hazards=None, ): """Construct a mock feed entry for testing purposes.""" feed_entry = MagicMock() feed_entry.external_id = external_id feed_entry.title = title feed_entry.alert_level = alert_level feed_entry.distance_to_home = distance_to_home feed_entry.coordinates = coordinates feed_entry.attribution = attribution feed_entry.activity = activity feed_entry.hazards = hazards return feed_entry
Create a mock GeoJSON Events config entry.
def config_entry() -> MockConfigEntry: """Create a mock GeoJSON Events config entry.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_URL: URL, CONF_LATITUDE: -41.2, CONF_LONGITUDE: 174.7, CONF_RADIUS: 25.0, }, title=f"{URL}, -41.2, 174.7", unique_id=f"{URL}, -41.2, 174.7", )
Mock geo_json_events entry setup.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock geo_json_events entry setup.""" with patch( "homeassistant.components.geo_json_events.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id: str, title: str, distance_to_home: float, coordinates: tuple[float, float], properties: dict[str, Any] | None = None, ) -> MagicMock: """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.properties = properties return feed_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."""
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
Initialize components.
def setup_comp(hass): """Initialize components.""" mock_component(hass, "group") hass.loop.run_until_complete( async_setup_component( hass, zone.DOMAIN, { "zone": { "name": "test", "latitude": 32.880837, "longitude": -117.237561, "radius": 250, } }, ) )
Pytest fixture for homeassistant.components.geo_rss_events.sensor.GenericFeed.
def mock_feed(): """Pytest fixture for homeassistant.components.geo_rss_events.sensor.GenericFeed.""" with patch( "homeassistant.components.geo_rss_events.sensor.GenericFeed" ) as mock_feed: yield mock_feed
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, distance_to_home, coordinates, category ): """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 return feed_entry
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="", domain=DOMAIN, data={CONF_ACCESS_TOKEN: MOCK_ACCESS_TOKEN}, options={CONF_REPOSITORIES: [TEST_REPOSITORY]}, )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch("homeassistant.components.github.async_setup_entry", return_value=True): yield
Mock glances api.
def mock_api(): """Mock glances api.""" with patch("homeassistant.components.glances.Glances") as mock_api: mock_api.return_value.get_ha_sensor_data = AsyncMock( return_value=HA_SENSOR_DATA ) yield mock_api
Mock glances entry setup.
def glances_setup_fixture(): """Mock glances entry setup.""" with patch("homeassistant.components.glances.async_setup_entry", return_value=True): yield
Add config entry in Home Assistant.
def create_entry(hass: HomeAssistant): """Add config entry in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, data=CONF_DATA, unique_id=MAC, ) entry.add_to_hass(hass) return entry
Patch Goal Zero config flow.
def patch_config_flow_yeti(mocked_yeti): """Patch Goal Zero config flow.""" return patch( "homeassistant.components.goalzero.config_flow.Yeti", return_value=mocked_yeti, )
Set up inverter fixture.
def fixture_mock_inverter(): """Set up inverter fixture.""" mock_inverter = MagicMock(spec=Inverter) mock_inverter.serial_number = "dummy_serial_nr" mock_inverter.arm_version = 1 mock_inverter.arm_svn_version = 2 mock_inverter.arm_firmware = "dummy.arm.version" mock_inverter.firmware = "dummy.fw.version" mock_inverter.model_name = "MOCK" mock_inverter.rated_power = 10000 mock_inverter.dsp1_version = 3 mock_inverter.dsp2_version = 4 mock_inverter.dsp_svn_version = 5 mock_inverter.read_runtime_data = AsyncMock(return_value={}) return mock_inverter
Get a mock object of the inverter.
def mock_inverter(): """Get a mock object of the inverter.""" goodwe_inverter = AsyncMock() goodwe_inverter.serial_number = TEST_SERIAL return goodwe_inverter
Default access role to use for test_api_calendar in tests.
def test_calendar_access_role() -> str: """Default access role to use for test_api_calendar in tests.""" return "owner"
Return a test calendar object used in API responses.
def test_api_calendar(calendar_access_role: str) -> None: """Return a test calendar object used in API responses.""" return { **TEST_API_CALENDAR, "accessRole": calendar_access_role, }
Fixture that determines the 'track' setting in yaml config.
def calendars_config_track() -> bool: """Fixture that determines the 'track' setting in yaml config.""" return True
Fixture that determines the 'ignore_availability' setting in yaml config.
def calendars_config_ignore_availability() -> bool: """Fixture that determines the 'ignore_availability' setting in yaml config.""" return None
Fixture that creates an entity within the yaml configuration.
def calendars_config_entity( calendars_config_track: bool, calendars_config_ignore_availability: bool | None ) -> dict[str, Any]: """Fixture that creates an entity within the yaml configuration.""" entity = { "device_id": "backyard_light", "name": "Backyard Light", "search": "#Backyard", "track": calendars_config_track, } if calendars_config_ignore_availability is not None: entity["ignore_availability"] = calendars_config_ignore_availability return entity
Fixture that specifies the calendar yaml configuration.
def calendars_config(calendars_config_entity: dict[str, Any]) -> list[dict[str, Any]]: """Fixture that specifies the calendar yaml configuration.""" return [ { "cal_id": CALENDAR_ID, "entities": [calendars_config_entity], } ]
Fixture that prepares the google_calendars.yaml mocks.
def mock_calendars_yaml( hass: HomeAssistant, calendars_config: list[dict[str, Any]], ) -> Generator[Mock, None, None]: """Fixture that prepares the google_calendars.yaml mocks.""" mocked_open_function = mock_open( read_data=yaml.dump(calendars_config) if calendars_config else None ) with patch("homeassistant.components.google.open", mocked_open_function): yield mocked_open_function
Fixture for scopes used during test.
def token_scopes() -> list[str]: """Fixture for scopes used during test.""" return ["https://www.googleapis.com/auth/calendar"]
Expiration time for credentials used in the test.
def token_expiry() -> datetime.datetime: """Expiration time for credentials used in the test.""" # OAuth library returns an offset-naive timestamp return dt_util.utcnow().replace(tzinfo=None) + datetime.timedelta(hours=1)
Fixture that defines creds used in the test.
def creds( token_scopes: list[str], token_expiry: datetime.datetime ) -> OAuth2Credentials: """Fixture that defines creds used in the test.""" return OAuth2Credentials( access_token="ACCESS_TOKEN", client_id=CLIENT_ID, client_secret=CLIENT_SECRET, refresh_token="REFRESH_TOKEN", token_expiry=token_expiry, token_uri="http://example.com", user_agent="n/a", scopes=token_scopes, )
Fixture for token expiration value stored in the config entry.
def config_entry_token_expiry() -> float: """Fixture for token expiration value stored in the config entry.""" return time.time() + 86400
Fixture to set initial config entry options.
def config_entry_options() -> dict[str, Any] | None: """Fixture to set initial config entry options.""" return None
Fixture that returns the default config entry unique id.
def config_entry_unique_id() -> str: """Fixture that returns the default config entry unique id.""" return EMAIL_ADDRESS
Fixture to create a config entry for the integration.
def config_entry( config_entry_unique_id: str, token_scopes: list[str], config_entry_token_expiry: float, config_entry_options: dict[str, Any] | None, ) -> MockConfigEntry: """Fixture to create a config entry for the integration.""" return MockConfigEntry( domain=DOMAIN, unique_id=config_entry_unique_id, data={ "auth_implementation": DOMAIN, "token": { "access_token": "ACCESS_TOKEN", "refresh_token": "REFRESH_TOKEN", "scope": " ".join(token_scopes), "token_type": "Bearer", "expires_at": config_entry_token_expiry, }, }, options=config_entry_options, )
Fixture to construct a fake event list API response.
def mock_events_list( aioclient_mock: AiohttpClientMocker, ) -> ApiResult: """Fixture to construct a fake event list API response.""" def _put_result( response: dict[str, Any], calendar_id: str | None = None, exc: ClientError | None = None, ) -> None: if calendar_id is None: calendar_id = CALENDAR_ID resp = { **response, "nextSyncToken": "sync-token", } aioclient_mock.get( f"{API_BASE_URL}/calendars/{calendar_id}/events", json=resp, exc=exc, ) return _put_result
Fixture to construct an API response containing event items.
def mock_events_list_items( mock_events_list: Callable[[dict[str, Any]], None], ) -> Callable[[list[dict[str, Any]]], None]: """Fixture to construct an API response containing event items.""" def _put_items(items: list[dict[str, Any]]) -> None: mock_events_list({"items": items}) return _put_items
Fixture to construct a fake calendar list API response.
def mock_calendars_list( aioclient_mock: AiohttpClientMocker, ) -> ApiResult: """Fixture to construct a fake calendar list API response.""" def _result(response: dict[str, Any], exc: ClientError | None = None) -> None: resp = { **response, "nextSyncToken": "sync-token", } aioclient_mock.get( f"{API_BASE_URL}/users/me/calendarList", json=resp, exc=exc, ) return _result
Fixture for returning a calendar get response.
def mock_calendar_get( aioclient_mock: AiohttpClientMocker, ) -> Callable[[...], None]: """Fixture for returning a calendar get response.""" def _result( calendar_id: str, response: dict[str, Any], exc: ClientError | None = None, status: http.HTTPStatus = http.HTTPStatus.OK, ) -> None: aioclient_mock.get( f"{API_BASE_URL}/calendars/{calendar_id}", json=response, exc=exc, status=status, ) return _result