response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Create a mock config entry.
def pvpc_aioclient_mock(aioclient_mock: AiohttpClientMocker): """Create a mock config entry.""" mask_url_public = ( "https://api.esios.ree.es/archives/70/download_json?locale=es&date={0}" ) mask_url_esios = ( "https://api.esios.ree.es/indicators/{0}" "?start_date={1}T00:00&end_date={1}T23:59" ) example_day = "2023-01-06" aioclient_mock.get( mask_url_public.format(example_day), text=load_fixture(f"{DOMAIN}/{FIXTURE_JSON_PUBLIC_DATA_2023_01_06}"), ) for esios_ind in _ESIOS_INDICATORS_FOR_EACH_SENSOR: aioclient_mock.get( mask_url_esios.format(esios_ind, example_day), text=load_fixture(f"{DOMAIN}/{FIXTURE_JSON_ESIOS_DATA_PVPC_2023_01_06}"), ) # simulate missing days aioclient_mock.get( mask_url_public.format("2023-01-07"), status=HTTPStatus.OK, text='{"message":"No values for specified archive"}', ) for esios_ind in _ESIOS_INDICATORS_FOR_EACH_SENSOR: aioclient_mock.get( mask_url_esios.format(esios_ind, "2023-01-07"), status=HTTPStatus.OK, text=( '{"indicator":{"name":"Término de facturación de energía activa del ' 'PVPC 2.0TD","short_name":"PVPC T. 2.0TD","id":1001,"composited":false,' '"step_type":"linear","disaggregated":true,"magnitud":' '[{"name":"Precio","id":23}],"tiempo":[{"name":"Hora","id":4}],"geos":[],' '"values_updated_at":null,"values":[]}}' ).replace("1001", esios_ind), ) # simulate bad authentication for esios_ind in _ESIOS_INDICATORS_FOR_EACH_SENSOR: aioclient_mock.get( mask_url_esios.format(esios_ind, "2023-01-08"), status=HTTPStatus.UNAUTHORIZED, text="HTTP Token: Access denied.", ) return aioclient_mock
Mock qbittorrent entry setup.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock qbittorrent entry setup.""" with patch( "homeassistant.components.qbittorrent.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock the qbittorrent API.
def mock_api() -> Generator[requests_mock.Mocker, None, None]: """Mock the qbittorrent API.""" with requests_mock.Mocker() as mocker: mocker.get("http://localhost:8080/api/v2/app/preferences", status_code=403) mocker.get("http://localhost:8080/api/v2/transfer/speedLimitsMode") mocker.post("http://localhost:8080/api/v2/auth/login", text="Ok.") yield mocker
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Construct a mock feed entry for testing purposes.
def _generate_mock_feed_entry( external_id, title, distance_to_home, coordinates, category=None, attribution=None, published=None, updated=None, status=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.attribution = attribution feed_entry.published = published feed_entry.updated = updated feed_entry.status = status return feed_entry
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.qnap.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock qnap connection.
def qnap_connect(mock_get_source_ip: None) -> Generator[MagicMock, None, None]: """Mock qnap connection.""" with patch( "homeassistant.components.qnap.config_flow.QNAPStats", autospec=True ) as host_mock_class: host_mock = host_mock_class.return_value host_mock.get_system_stats.return_value = TEST_SYSTEM_STATS yield host_mock
Return a set of devices as a response.
def qs_devices(): """Return a set of devices as a response.""" return [ { "id": "@a00001", "name": "Switch 1", "type": "rel", "val": "OFF", "time": "1522777506", "rssi": "51%", }, { "id": "@a00002", "name": "Light 2", "type": "rel", "val": "ON", "time": "1522777507", "rssi": "45%", }, { "id": "@a00003", "name": "Dim 3", "type": "dim", "val": "280c00", "time": "1522777544", "rssi": "62%", }, ]
Mock zeroconf in all tests.
def use_mocked_zeroconf(mock_async_zeroconf): """Mock zeroconf in all tests."""
Mock connection.
def rabbitair_connect() -> Generator[None, None, None]: """Mock connection.""" with ( patch("rabbitair.UdpClient.get_info", return_value=get_mock_info()), patch("rabbitair.UdpClient.get_state", return_value=get_mock_state()), ): yield
Return a mock device info instance.
def get_mock_info(mac: str = TEST_MAC) -> Mock: """Return a mock device info instance.""" mock_info = Mock() mock_info.mac = mac return mock_info
Return a mock device state instance.
def get_mock_state( model: Model | None = Model.A3, main_firmware: str | None = TEST_HARDWARE, power: bool | None = True, mode: Mode | None = Mode.Auto, speed: Speed | None = Speed.Low, wifi_firmware: str | None = TEST_FIRMWARE, ) -> Mock: """Return a mock device state instance.""" mock_state = Mock() mock_state.model = model mock_state.main_firmware = main_firmware mock_state.power = power mock_state.mode = mode mock_state.speed = speed mock_state.wifi_firmware = wifi_firmware return mock_state
Mock radarr connection.
def mock_connection( aioclient_mock: AiohttpClientMocker, url: str = URL, error: bool = False, invalid_auth: bool = False, windows: bool = False, single_return: bool = False, ) -> None: """Mock radarr connection.""" if error: mock_connection_error( aioclient_mock, url=url, ) return if invalid_auth: mock_connection_invalid_auth( aioclient_mock, url=url, ) return aioclient_mock.get( f"{url}/api/v3/system/status", text=load_fixture("radarr/system-status.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( f"{url}/api/v3/command", text=load_fixture("radarr/command.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( f"{url}/api/v3/health", text=load_fixture("radarr/health.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( f"{url}/api/v3/queue", text=load_fixture("radarr/queue.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) root_folder_fixture = "rootfolder-linux" if windows: root_folder_fixture = "rootfolder-windows" if single_return: root_folder_fixture = f"single-{root_folder_fixture}" aioclient_mock.get( f"{url}/api/v3/rootfolder", text=load_fixture(f"radarr/{root_folder_fixture}.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, ) aioclient_mock.get( f"{url}/api/v3/movie", text=load_fixture("radarr/movie.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, )
Mock radarr connection.
def mock_calendar( aioclient_mock: AiohttpClientMocker, url: str = URL, ) -> None: """Mock radarr connection.""" aioclient_mock.get( f"{url}/api/v3/calendar", text=load_fixture("radarr/calendar.json"), headers={"Content-Type": CONTENT_TYPE_JSON}, )
Mock radarr connection errors.
def mock_connection_error( aioclient_mock: AiohttpClientMocker, url: str = URL, ) -> None: """Mock radarr connection errors.""" aioclient_mock.get(f"{url}/api/v3/system/status", exc=ClientError)
Mock radarr invalid auth errors.
def mock_connection_invalid_auth( aioclient_mock: AiohttpClientMocker, url: str = URL, ) -> None: """Mock radarr invalid auth errors.""" aioclient_mock.get(f"{url}/api/v3/command", status=HTTPStatus.UNAUTHORIZED) aioclient_mock.get(f"{url}/api/v3/movie", status=HTTPStatus.UNAUTHORIZED) aioclient_mock.get(f"{url}/api/v3/queue", status=HTTPStatus.UNAUTHORIZED) aioclient_mock.get(f"{url}/api/v3/rootfolder", status=HTTPStatus.UNAUTHORIZED) aioclient_mock.get(f"{url}/api/v3/system/status", status=HTTPStatus.UNAUTHORIZED) aioclient_mock.get(f"{url}/api/v3/calendar", status=HTTPStatus.UNAUTHORIZED)
Mock radarr server errors.
def mock_connection_server_error( aioclient_mock: AiohttpClientMocker, url: str = URL, ) -> None: """Mock radarr server errors.""" aioclient_mock.get(f"{url}/api/v3/command", status=HTTPStatus.INTERNAL_SERVER_ERROR) aioclient_mock.get(f"{url}/api/v3/movie", status=HTTPStatus.INTERNAL_SERVER_ERROR) aioclient_mock.get(f"{url}/api/v3/queue", status=HTTPStatus.INTERNAL_SERVER_ERROR) aioclient_mock.get( f"{url}/api/v3/rootfolder", status=HTTPStatus.INTERNAL_SERVER_ERROR ) aioclient_mock.get( f"{url}/api/v3/system/status", status=HTTPStatus.INTERNAL_SERVER_ERROR ) aioclient_mock.get( f"{url}/api/v3/calendar", status=HTTPStatus.INTERNAL_SERVER_ERROR )
Patch the async entry setup of radarr.
def patch_async_setup_entry(return_value=True): """Patch the async entry setup of radarr.""" return patch( "homeassistant.components.radarr.async_setup_entry", return_value=return_value, )
Create Radarr entry in Home Assistant.
def create_entry(hass: HomeAssistant) -> MockConfigEntry: """Create Radarr entry in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, data={ CONF_URL: URL, CONF_API_KEY: API_KEY, CONF_VERIFY_SSL: False, }, ) 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( title="My Radios", domain=DOMAIN, data={}, )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.radio_browser.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Fixture to specify platforms to test.
def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return []
Fixture for setting up the default platforms.
def setup_platforms( hass: HomeAssistant, platforms: list[str], ) -> None: """Fixture for setting up the default platforms.""" with patch(f"homeassistant.components.{DOMAIN}.PLATFORMS", platforms): yield
Context manager to mock aiohttp client.
def aioclient_mock(hass: HomeAssistant) -> Generator[AiohttpClientMocker, None, None]: """Context manager to mock aiohttp client.""" mocker = AiohttpClientMocker() def create_session(): session = mocker.create_session(hass.loop) async def close_session(event): """Close session.""" await session.close() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, close_session) return session with ( patch( "homeassistant.components.rainbird.async_create_clientsession", side_effect=create_session, ), patch( "homeassistant.components.rainbird.config_flow.async_create_clientsession", side_effect=create_session, ), ): yield mocker
Create a fake API response.
def rainbird_json_response(result: dict[str, str]) -> bytes: """Create a fake API response.""" return encryption.encrypt( f'{{"jsonrpc": "2.0", "result": {json.dumps(result)}, "id": 1}} ', PASSWORD, )
Create a fake AiohttpClientMockResponse.
def mock_json_response(result: dict[str, str]) -> AiohttpClientMockResponse: """Create a fake AiohttpClientMockResponse.""" return AiohttpClientMockResponse( "POST", URL, response=rainbird_json_response(result) )
Create a fake AiohttpClientMockResponse.
def mock_response(data: str) -> AiohttpClientMockResponse: """Create a fake AiohttpClientMockResponse.""" return mock_json_response({"data": data})
Create a fake AiohttpClientMockResponse.
def mock_response_error( status: HTTPStatus = HTTPStatus.SERVICE_UNAVAILABLE, ) -> AiohttpClientMockResponse: """Create a fake AiohttpClientMockResponse.""" return AiohttpClientMockResponse("POST", URL, status=status)
Mock response to return available stations.
def mock_station_response() -> str: """Mock response to return available stations.""" return AVAILABLE_STATIONS_RESPONSE
Mock response to return zone states.
def mock_zone_state_response() -> str: """Mock response to return zone states.""" return ZONE_STATE_OFF_RESPONSE
Mock response to return rain sensor state.
def mock_rain_response() -> str: """Mock response to return rain sensor state.""" return RAIN_SENSOR_OFF
Mock response to return rain delay state.
def mock_rain_delay_response() -> str: """Mock response to return rain delay state.""" return RAIN_DELAY_OFF
Mock response to return rain delay state.
def mock_model_and_version_response() -> str: """Mock response to return rain delay state.""" return MODEL_AND_VERSION_RESPONSE
Fixture to set up a list of fake API responsees for tests to extend. These are returned in the order they are requested by the update coordinator.
def mock_api_responses( model_and_version_response: str, stations_response: str, zone_state_response: str, rain_response: str, rain_delay_response: str, ) -> list[str]: """Fixture to set up a list of fake API responsees for tests to extend. These are returned in the order they are requested by the update coordinator. """ return [ model_and_version_response, stations_response, zone_state_response, rain_response, rain_delay_response, ]
Fixture to set up a list of fake API responsees for tests to extend.
def mock_responses(api_responses: list[str]) -> list[AiohttpClientMockResponse]: """Fixture to set up a list of fake API responsees for tests to extend.""" return [mock_response(api_response) for api_response in api_responses]
Fixture for command mocking for fake responses to the API url.
def handle_responses( aioclient_mock: AiohttpClientMocker, responses: list[AiohttpClientMockResponse], ) -> None: """Fixture for command mocking for fake responses to the API url.""" async def handle(method, url, data) -> AiohttpClientMockResponse: return responses.pop(0) aioclient_mock.post(URL, side_effect=handle)
Fixture to specify platforms to test.
def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return [Platform.BINARY_SENSOR]
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return [Platform.CALENDAR]
Set the time zone for the tests.
def set_time_zone(hass: HomeAssistant): """Set the time zone for the tests.""" hass.config.set_time_zone("America/Regina")
Fixture containing fake irrigation schedule.
def mock_schedule_responses() -> list[str]: """Fixture containing fake irrigation schedule.""" return SCHEDULE_RESPONSES
Fixture to insert device responses for the irrigation schedule.
def mock_insert_schedule_response( mock_schedule_responses: list[str], responses: list[AiohttpClientMockResponse] ) -> None: """Fixture to insert device responses for the irrigation schedule.""" responses.extend( [mock_response(api_response) for api_response in mock_schedule_responses] )
Fetch calendar events from the HTTP API.
def get_events_fixture( hass_client: Callable[..., Awaitable[ClientSession]], ) -> GetEventsFn: """Fetch calendar events from the HTTP API.""" async def _fetch(start: str, end: str) -> list[dict[str, Any]]: client = await hass_client() response = await client.get( f"/api/calendars/{TEST_ENTITY}?start={urllib.parse.quote(start)}&end={urllib.parse.quote(end)}" ) assert response.status == HTTPStatus.OK results = await response.json() return [{k: event[k] for k in ("summary", "start", "end")} for event in results] return _fetch
Set up fake serial number response when testing the connection.
def mock_responses() -> list[AiohttpClientMockResponse]: """Set up fake serial number response when testing the connection.""" return [mock_response(SERIAL_RESPONSE), mock_json_response(WIFI_PARAMS_RESPONSE)]
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return [Platform.NUMBER]
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return [Platform.SENSOR]
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return [Platform.SWITCH]
Return a config entry.
def config_entry_200(hass): """Return a config entry.""" entry = MockConfigEntry( domain="rainforest_eagle", data={ CONF_CLOUD_ID: MOCK_CLOUD_ID, CONF_HOST: "192.168.1.55", CONF_INSTALL_CODE: "abcdefgh", CONF_HARDWARE_ADDRESS: "mock-hw-address", CONF_TYPE: TYPE_EAGLE_200, }, ) entry.add_to_hass(hass) return entry
Mock a functioning RAVEn device.
def mock_device(): """Mock a functioning RAVEn device.""" device = create_mock_device() with patch( "homeassistant.components.rainforest_raven.config_flow.RAVEnSerialDevice", return_value=device, ): yield device
Mock a device which fails to open.
def mock_device_no_open(mock_device): """Mock a device which fails to open.""" mock_device.__aenter__.side_effect = RAVEnConnectionError mock_device.open.side_effect = RAVEnConnectionError return mock_device
Mock a device which fails to read or parse raw data.
def mock_device_comm_error(mock_device): """Mock a device which fails to read or parse raw data.""" mock_device.get_meter_list.side_effect = RAVEnConnectionError mock_device.get_meter_info.side_effect = RAVEnConnectionError return mock_device
Mock a device which times out when queried.
def mock_device_timeout(mock_device): """Mock a device which times out when queried.""" mock_device.get_meter_list.side_effect = TimeoutError mock_device.get_meter_info.side_effect = TimeoutError return mock_device
Mock serial port list.
def mock_comports(): """Mock serial port list.""" port = serial.tools.list_ports_common.ListPortInfo(DISCOVERY_INFO.device) port.serial_number = DISCOVERY_INFO.serial_number port.manufacturer = DISCOVERY_INFO.manufacturer port.device = DISCOVERY_INFO.device port.description = DISCOVERY_INFO.description port.pid = int(DISCOVERY_INFO.pid, 0) port.vid = int(DISCOVERY_INFO.vid, 0) comports = [port] with patch("serial.tools.list_ports.comports", return_value=comports): yield comports
Mock a functioning RAVEn device.
def mock_device(): """Mock a functioning RAVEn device.""" mock_device = create_mock_device() with patch( "homeassistant.components.rainforest_raven.coordinator.RAVEnSerialDevice", return_value=mock_device, ): yield mock_device
Mock a functioning RAVEn device.
def mock_device(): """Mock a functioning RAVEn device.""" mock_device = create_mock_device() with patch( "homeassistant.components.rainforest_raven.coordinator.RAVEnSerialDevice", return_value=mock_device, ): yield mock_device
Mock a functioning RAVEn device.
def mock_device(): """Mock a functioning RAVEn device.""" mock_device = create_mock_device() with patch( "homeassistant.components.rainforest_raven.coordinator.RAVEnSerialDevice", return_value=mock_device, ): yield mock_device
Mock a functioning RAVEn device.
def mock_device(): """Mock a functioning RAVEn device.""" mock_device = create_mock_device() with patch( "homeassistant.components.rainforest_raven.coordinator.RAVEnSerialDevice", return_value=mock_device, ): yield mock_device
Create a mock instance of RAVEnStreamDevice.
def create_mock_device(): """Create a mock instance of RAVEnStreamDevice.""" device = AsyncMock() device.__aenter__.return_value = device device.get_current_price.return_value = PRICE_CLUSTER device.get_current_summation_delivered.return_value = SUMMATION device.get_device_info.return_value = DEVICE_INFO device.get_instantaneous_demand.return_value = DEMAND device.get_meter_list.return_value = METER_LIST device.get_meter_info.side_effect = lambda meter: METER_INFO.get(meter) device.get_network_info.return_value = NETWORK_INFO return device
Create a mock config entry for a RAVEn device.
def create_mock_entry(no_meters=False): """Create a mock config entry for a RAVEn device.""" return MockConfigEntry( domain=DOMAIN, data={ CONF_DEVICE: DISCOVERY_INFO.device, CONF_MAC: [] if no_meters else [METER_INFO[None].meter_mac_id.hex()], }, )
Define a regenmaschine client.
def client_fixture(controller, controller_mac): """Define a regenmaschine client.""" return AsyncMock(load_local=AsyncMock(), controllers={controller_mac: controller})
Define a config entry data fixture.
def config_fixture(hass): """Define a config entry data fixture.""" return { CONF_IP_ADDRESS: "192.168.1.100", CONF_PASSWORD: "password", CONF_PORT: 8080, CONF_SSL: True, }
Define a config entry fixture.
def config_entry_fixture(hass, config, controller_mac): """Define a config entry fixture.""" entry = MockConfigEntry(domain=DOMAIN, unique_id=controller_mac, data=config) entry.add_to_hass(hass) return entry
Define a regenmaschine controller.
def controller_fixture( controller_mac, data_api_versions, data_diagnostics_current, data_machine_firmare_update_status, data_programs, data_provision_settings, data_restrictions_current, data_restrictions_universal, data_zones, ): """Define a regenmaschine controller.""" controller = AsyncMock() controller.api_version = "4.5.0" controller.hardware_version = "3" controller.name = "12345" controller.mac = controller_mac controller.software_version = "4.0.925" controller.api.versions.return_value = data_api_versions controller.diagnostics.current.return_value = data_diagnostics_current controller.machine.get_firmware_update_status.return_value = ( data_machine_firmare_update_status ) controller.programs.all.return_value = data_programs controller.provisioning.settings.return_value = data_provision_settings controller.restrictions.current.return_value = data_restrictions_current controller.restrictions.universal.return_value = data_restrictions_universal controller.zones.all.return_value = data_zones return controller
Define a controller MAC address.
def controller_mac_fixture(): """Define a controller MAC address.""" return "aa:bb:cc:dd:ee:ff"
Define API version data.
def data_api_versions_fixture(): """Define API version data.""" return json.loads(load_fixture("api_versions_data.json", "rainmachine"))
Define current diagnostics data.
def data_diagnostics_current_fixture(): """Define current diagnostics data.""" return json.loads(load_fixture("diagnostics_current_data.json", "rainmachine"))
Define machine firmware update status data.
def data_machine_firmare_update_status_fixture(): """Define machine firmware update status data.""" return json.loads( load_fixture("machine_firmware_update_status_data.json", "rainmachine") )
Define program data.
def data_programs_fixture(): """Define program data.""" return json.loads(load_fixture("programs_data.json", "rainmachine"))
Define provisioning settings data.
def data_provision_settings_fixture(): """Define provisioning settings data.""" return json.loads(load_fixture("provision_settings_data.json", "rainmachine"))
Define current restrictions settings data.
def data_restrictions_current_fixture(): """Define current restrictions settings data.""" return json.loads(load_fixture("restrictions_current_data.json", "rainmachine"))
Define universal restrictions settings data.
def data_restrictions_universal_fixture(): """Define universal restrictions settings data.""" return json.loads(load_fixture("restrictions_universal_data.json", "rainmachine"))
Define zone data.
def data_zones_fixture(): """Define zone data.""" return json.loads(load_fixture("zones_data.json", "rainmachine"))
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Mock the rpi_power integration.
def mock_rpi_power(): """Mock the rpi_power integration.""" with patch( "homeassistant.components.rpi_power.async_setup_entry", return_value=True, ): yield
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="My Car", domain=DOMAIN, data={CONF_LICENSE_PLATE: "11ZKZ3"}, unique_id="11ZKZ3", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch("homeassistant.components.rdw.async_setup_entry", return_value=True): yield
Return a mocked RDW client.
def mock_rdw_config_flow() -> Generator[None, MagicMock, None]: """Return a mocked RDW client.""" with patch( "homeassistant.components.rdw.config_flow.RDW", autospec=True ) as rdw_mock: rdw = rdw_mock.return_value rdw.vehicle.return_value = Vehicle.from_json(load_fixture("rdw/11ZKZ3.json")) yield rdw
Return a mocked WLED client.
def mock_rdw(request: pytest.FixtureRequest) -> Generator[None, MagicMock, None]: """Return a mocked WLED client.""" fixture: str = "rdw/11ZKZ3.json" if hasattr(request, "param") and request.param: fixture = request.param vehicle = Vehicle.from_json(load_fixture(fixture)) with patch("homeassistant.components.rdw.RDW", autospec=True) as rdw_mock: rdw = rdw_mock.return_value rdw.vehicle.return_value = vehicle yield rdw
Define a fixture to return a mocked aiopurple API object.
def client_fixture(pickup_events): """Define a fixture to return a mocked aiopurple API object.""" return Mock(async_get_pickup_events=AsyncMock(return_value=pickup_events))
Define a config entry fixture.
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=f"{TEST_PLACE_ID}, {TEST_SERVICE_ID}", 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_PLACE_ID: TEST_PLACE_ID, CONF_SERVICE_ID: TEST_SERVICE_ID, }
Define a list of pickup events.
def pickup_events_fixture(): """Define a list of pickup events.""" return [ PickupEvent( date(2022, 1, 23), [PickupType("garbage", "Trash Collection")], "The Sun" ) ]
Trigger an adhoc statistics run.
def do_adhoc_statistics(hass: HomeAssistant, **kwargs: Any) -> None: """Trigger an adhoc statistics run.""" if not (start := kwargs.get("start")): start = statistics.get_start_time() get_instance(hass).queue_task(StatisticsTask(start, False))
Block till recording is done.
def wait_recording_done(hass: HomeAssistant) -> None: """Block till recording is done.""" hass.block_till_done() trigger_db_commit(hass) hass.block_till_done() recorder.get_instance(hass).block_till_done() hass.block_till_done()
Force the recorder to commit.
def trigger_db_commit(hass: HomeAssistant) -> None: """Force the recorder to commit.""" recorder.get_instance(hass)._async_commit(dt_util.utcnow())
Force the recorder to commit. Async friendly.
def async_trigger_db_commit(hass: HomeAssistant) -> None: """Force the recorder to commit. Async friendly.""" recorder.get_instance(hass)._async_commit(dt_util.utcnow())
Corrupt an sqlite3 database file.
def corrupt_db_file(test_db_file): """Corrupt an sqlite3 database file.""" with open(test_db_file, "w+") as fhandle: fhandle.seek(200) fhandle.write("I am a corrupt db" * 100)
Test version of create_engine that initializes with old schema. This simulates an existing db with the old schema.
def create_engine_test(*args, **kwargs): """Test version of create_engine that initializes with old schema. This simulates an existing db with the old schema. """ engine = create_engine(*args, **kwargs) db_schema_0.Base.metadata.create_all(engine) return engine
Return information about current run from the database.
def run_information_with_session( session: Session, point_in_time: datetime | None = None ) -> RecorderRuns | None: """Return information about current run from the database.""" recorder_runs = RecorderRuns query = session.query(recorder_runs) if point_in_time: query = query.filter( (recorder_runs.start < point_in_time) & (recorder_runs.end > point_in_time) ) if (res := query.first()) is not None: session.expunge(res) return cast(RecorderRuns, res) return res
Call statistics_during_period with defaults for simpler tests.
def statistics_during_period( hass: HomeAssistant, start_time: datetime, end_time: datetime | None = None, statistic_ids: set[str] | None = None, period: Literal["5minute", "day", "hour", "week", "month"] = "hour", units: dict[str, str] | None = None, types: set[Literal["last_reset", "max", "mean", "min", "state", "sum"]] | None = None, ) -> dict[str, list[dict[str, Any]]]: """Call statistics_during_period with defaults for simpler tests.""" if statistic_ids is not None and not isinstance(statistic_ids, set): statistic_ids = set(statistic_ids) if types is None: types = {"last_reset", "max", "mean", "min", "state", "sum"} return statistics.statistics_during_period( hass, start_time, end_time, statistic_ids, period, units, types )
Assert that two states are equal, ignoring context.
def assert_states_equal_without_context(state: State, other: State) -> None: """Assert that two states are equal, ignoring context.""" assert_states_equal_without_context_and_last_changed(state, other) assert state.last_changed == other.last_changed assert state.last_reported == other.last_reported
Assert that two states are equal, ignoring context and last_changed.
def assert_states_equal_without_context_and_last_changed( state: State, other: State ) -> None: """Assert that two states are equal, ignoring context and last_changed.""" assert state.state == other.state assert state.attributes == other.attributes assert state.last_updated == other.last_updated
Assert that multiple states are equal, ignoring context and last_changed.
def assert_multiple_states_equal_without_context_and_last_changed( states: Iterable[State], others: Iterable[State] ) -> None: """Assert that multiple states are equal, ignoring context and last_changed.""" states_list = list(states) others_list = list(others) assert len(states_list) == len(others_list) for i, state in enumerate(states_list): assert_states_equal_without_context_and_last_changed(state, others_list[i])
Assert that multiple states are equal, ignoring context.
def assert_multiple_states_equal_without_context( states: Iterable[State], others: Iterable[State] ) -> None: """Assert that multiple states are equal, ignoring context.""" states_list = list(states) others_list = list(others) assert len(states_list) == len(others_list) for i, state in enumerate(states_list): assert_states_equal_without_context(state, others_list[i])
Assert that two events are equal, ignoring context.
def assert_events_equal_without_context(event: Event, other: Event) -> None: """Assert that two events are equal, ignoring context.""" assert event.data == other.data assert event.event_type == other.event_type assert event.origin == other.origin assert event.time_fired == other.time_fired
Assert that two dicts of states are equal, ignoring context.
def assert_dict_of_states_equal_without_context( states: dict[str, list[State]], others: dict[str, list[State]] ) -> None: """Assert that two dicts of states are equal, ignoring context.""" assert len(states) == len(others) for entity_id, state in states.items(): assert_multiple_states_equal_without_context(state, others[entity_id])
Assert that two dicts of states are equal, ignoring context and last_changed.
def assert_dict_of_states_equal_without_context_and_last_changed( states: dict[str, list[State]], others: dict[str, list[State]] ) -> None: """Assert that two dicts of states are equal, ignoring context and last_changed.""" assert len(states) == len(others) for entity_id, state in states.items(): assert_multiple_states_equal_without_context_and_last_changed( state, others[entity_id] )
Record some test states. We inject a bunch of state updates temperature sensors.
def record_states(hass): """Record some test states. We inject a bunch of state updates temperature sensors. """ mp = "media_player.test" sns1 = "sensor.test1" sns2 = "sensor.test2" sns3 = "sensor.test3" sns4 = "sensor.test4" sns1_attr = { "device_class": "temperature", "state_class": "measurement", "unit_of_measurement": UnitOfTemperature.CELSIUS, } sns2_attr = { "device_class": "humidity", "state_class": "measurement", "unit_of_measurement": "%", } sns3_attr = {"device_class": "temperature"} sns4_attr = {} def set_state(entity_id, state, **kwargs): """Set the state.""" hass.states.set(entity_id, state, **kwargs) wait_recording_done(hass) return hass.states.get(entity_id) zero = dt_util.utcnow() one = zero + timedelta(seconds=1 * 5) two = one + timedelta(seconds=15 * 5) three = two + timedelta(seconds=30 * 5) four = three + timedelta(seconds=15 * 5) states = {mp: [], sns1: [], sns2: [], sns3: [], sns4: []} with freeze_time(one) as freezer: states[mp].append( set_state(mp, "idle", attributes={"media_title": str(sentinel.mt1)}) ) states[sns1].append(set_state(sns1, "10", attributes=sns1_attr)) states[sns2].append(set_state(sns2, "10", attributes=sns2_attr)) states[sns3].append(set_state(sns3, "10", attributes=sns3_attr)) states[sns4].append(set_state(sns4, "10", attributes=sns4_attr)) freezer.move_to(one + timedelta(microseconds=1)) states[mp].append( set_state(mp, "YouTube", attributes={"media_title": str(sentinel.mt2)}) ) freezer.move_to(two) states[sns1].append(set_state(sns1, "15", attributes=sns1_attr)) states[sns2].append(set_state(sns2, "15", attributes=sns2_attr)) states[sns3].append(set_state(sns3, "15", attributes=sns3_attr)) states[sns4].append(set_state(sns4, "15", attributes=sns4_attr)) freezer.move_to(three) states[sns1].append(set_state(sns1, "20", attributes=sns1_attr)) states[sns2].append(set_state(sns2, "20", attributes=sns2_attr)) states[sns3].append(set_state(sns3, "20", attributes=sns3_attr)) states[sns4].append(set_state(sns4, "20", attributes=sns4_attr)) return zero, four, states
Convert pending states to use states_metadata.
def convert_pending_states_to_meta(instance: Recorder, session: Session) -> None: """Convert pending states to use states_metadata.""" entity_ids: set[str] = set() states: set[States] = set() states_meta_objects: dict[str, StatesMeta] = {} for session_object in session: if isinstance(session_object, States): entity_ids.add(session_object.entity_id) states.add(session_object) entity_id_to_metadata_ids = instance.states_meta_manager.get_many( entity_ids, session, True ) for state in states: entity_id = state.entity_id state.entity_id = None state.attributes = None state.event_id = None if metadata_id := entity_id_to_metadata_ids.get(entity_id): state.metadata_id = metadata_id continue if entity_id not in states_meta_objects: states_meta_objects[entity_id] = StatesMeta(entity_id=entity_id) state.states_meta_rel = states_meta_objects[entity_id]
Convert pending events to use event_type_ids.
def convert_pending_events_to_event_types(instance: Recorder, session: Session) -> None: """Convert pending events to use event_type_ids.""" event_types: set[str] = set() events: set[Events] = set() event_types_objects: dict[str, EventTypes] = {} for session_object in session: if isinstance(session_object, Events): event_types.add(session_object.event_type) events.add(session_object) event_type_to_event_type_ids = instance.event_type_manager.get_many( event_types, session, True ) manually_added_event_types: list[str] = [] for event in events: event_type = event.event_type event.event_type = None event.event_data = None event.origin = None if event_type_id := event_type_to_event_type_ids.get(event_type): event.event_type_id = event_type_id continue if event_type not in event_types_objects: event_types_objects[event_type] = EventTypes(event_type=event_type) manually_added_event_types.append(event_type) event.event_type_rel = event_types_objects[event_type] for event_type in manually_added_event_types: instance.event_type_manager._non_existent_event_types.pop(event_type, None)
Test version of create_engine that initializes with old schema. This simulates an existing db with the old schema.
def create_engine_test_for_schema_version_postfix( *args, schema_version_postfix: str, **kwargs ): """Test version of create_engine that initializes with old schema. This simulates an existing db with the old schema. """ schema_module = get_schema_module_path(schema_version_postfix) importlib.import_module(schema_module) old_db_schema = sys.modules[schema_module] engine = create_engine(*args, **kwargs) old_db_schema.Base.metadata.create_all(engine) with Session(engine) as session: session.add( recorder.db_schema.StatisticsRuns(start=statistics.get_start_time()) ) session.add( recorder.db_schema.SchemaChanges( schema_version=old_db_schema.SCHEMA_VERSION ) ) session.commit() return engine