response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Fixture for capturing event creation.
def mock_insert_event( aioclient_mock: AiohttpClientMocker, ) -> Callable[[...], None]: """Fixture for capturing event creation.""" def _expect_result( calendar_id: str = CALENDAR_ID, exc: ClientError | None = None ) -> None: aioclient_mock.post( f"{API_BASE_URL}/calendars/{calendar_id}/events", exc=exc, ) return _expect_result
Set the time zone for the tests.
def set_time_zone(hass): """Set the time zone for the tests.""" # Set our timezone to CST/Regina so we can check calculations # This keeps UTC-6 all year round hass.config.set_time_zone("America/Regina")
Fixture for setting up the integration.
def component_setup( hass: HomeAssistant, config_entry: MockConfigEntry ) -> ComponentSetup: """Fixture for setting up the integration.""" async def _setup_func() -> bool: assert await async_setup_component(hass, "application_credentials", {}) await async_import_client_credential( hass, DOMAIN, ClientCredential("client-id", "client-secret"), ) config_entry.add_to_hass(hass) return await hass.config_entries.async_setup(config_entry.entry_id) return _setup_func
Fixture that sets up the default API responses during integration setup.
def mock_test_setup( test_api_calendar, mock_calendars_list, ): """Fixture that sets up the default API responses during integration setup.""" mock_calendars_list({"items": [test_api_calendar]})
Create a url to get events during the specified time range.
def get_events_url(entity: str, start: str, end: str) -> str: """Create a url to get events during the specified time range.""" return f"/api/calendars/{entity}?start={urllib.parse.quote(start)}&end={urllib.parse.quote(end)}"
Create a test event with an arbitrary start/end time fetched from the api url.
def upcoming() -> dict[str, Any]: """Create a test event with an arbitrary start/end time fetched from the api url.""" now = dt_util.now() return { "start": {"dateTime": now.isoformat()}, "end": {"dateTime": (now + datetime.timedelta(minutes=5)).isoformat()}, }
Return a calendar API to return events created by upcoming().
def upcoming_event_url(entity: str = TEST_ENTITY) -> str: """Return a calendar API to return events created by upcoming().""" now = dt_util.now() start = (now - datetime.timedelta(minutes=60)).isoformat() end = (now + datetime.timedelta(minutes=60)).isoformat() return get_events_url(entity, start, end)
Fixture that sets up the default API responses during integration setup.
def mock_test_setup( test_api_calendar, mock_calendars_list, ): """Fixture that sets up the default API responses during integration setup.""" mock_calendars_list({"items": [test_api_calendar]})
Return a test client generator."".
def _get_test_client_generator( hass: HomeAssistant, aiohttp_client: ClientSessionGenerator, new_token: str ): """Return a test client generator."".""" async def auth_client() -> TestClient: return await aiohttp_client( hass.http.app, headers={"Authorization": f"Bearer {new_token}"} ) return auth_client
Assert that the two states are equal.
def assert_state(actual: State | None, expected: State | None) -> None: """Assert that the two states are equal.""" if actual is None or expected is None: assert actual == expected return assert actual.entity_id == expected.entity_id assert actual.state == expected.state assert actual.attributes == expected.attributes
Fixture for calling the add or create event service.
def add_event_call_service( hass: HomeAssistant, request: Any, ) -> Callable[dict[str, Any], Awaitable[None]]: """Fixture for calling the add or create event service.""" (domain, service_call, data, target) = request.param async def call_service(params: dict[str, Any]) -> None: await hass.services.async_call( domain, service_call, { **data, **params, "summary": TEST_EVENT_SUMMARY, "description": TEST_EVENT_DESCRIPTION, }, target=target, blocking=True, ) return call_service
Test async_redact_msg.
def test_redact_msg(): """Test async_redact_msg.""" messages = json.loads(load_fixture("data_redaction.json", "google_assistant")) agent_user_id = "333dee20-1234-1234-1234-2225a0d70d4c" for item in messages: assert async_redact_msg(item["raw"], agent_user_id) == item["redacted"]
Generate an HTTP header with bearer token authorization.
def auth_header(hass_access_token): """Generate an HTTP header with bearer token authorization.""" return {AUTHORIZATION: f"Bearer {hass_access_token}"}
Create web client for the Google Assistant API.
def assistant_client(event_loop, hass, hass_client_no_auth): """Create web client for the Google Assistant API.""" loop = event_loop loop.run_until_complete( setup.async_setup_component( hass, "google_assistant", { "google_assistant": { "project_id": PROJECT_ID, "entity_config": { "light.ceiling_lights": { "aliases": ["top lights", "ceiling lights"], "name": "Roof Lights", } }, } }, ) ) return loop.run_until_complete(hass_client_no_auth())
Set up a Home Assistant instance for these tests.
def hass_fixture(event_loop, hass): """Set up a Home Assistant instance for these tests.""" loop = event_loop # We need to do this to get access to homeassistant/turn_(on,off) loop.run_until_complete(setup.async_setup_component(hass, core.DOMAIN, {})) loop.run_until_complete(setup.async_setup_component(hass, "demo", {})) return hass
Test bad supported features.
def test_supported_features_string(caplog: pytest.LogCaptureFixture) -> None: """Test bad supported features.""" entity = helpers.GoogleEntity( None, MockConfig(), State("test.entity_id", "on", {"supported_features": "invalid"}), ) assert entity.is_supported() is False assert ( "Entity test.entity_id contains invalid supported_features value invalid" in caplog.text )
Test request data properties.
def test_request_data() -> None: """Test request data properties.""" config = MockConfig() data = helpers.RequestData( config, "test_user", SOURCE_LOCAL, "test_request_id", None ) assert data.is_local_request is True data = helpers.RequestData( config, "test_user", SOURCE_CLOUD, "test_request_id", None ) assert data.is_local_request is False
Test async_get_entities is cached.
def test_async_get_entities_cached(hass: HomeAssistant) -> None: """Test async_get_entities is cached.""" config = MockConfig() hass.states.async_set("light.ceiling_lights", "off") hass.states.async_set("light.bed_light", "off") hass.states.async_set("not_supported.not_supported", "off") google_entities = helpers.async_get_entities(hass, config) assert len(google_entities) == 2 assert config.is_supported_cache == { "light.bed_light": (None, True), "light.ceiling_lights": (None, True), "not_supported.not_supported": (None, False), } with patch( "homeassistant.components.google_assistant.helpers.GoogleEntity.traits", return_value=RuntimeError("Should not be called"), ): google_entities = helpers.async_get_entities(hass, config) assert len(google_entities) == 2 assert config.is_supported_cache == { "light.bed_light": (None, True), "light.ceiling_lights": (None, True), "not_supported.not_supported": (None, False), } hass.states.async_set("light.new", "on") google_entities = helpers.async_get_entities(hass, config) assert len(google_entities) == 3 assert config.is_supported_cache == { "light.bed_light": (None, True), "light.new": (None, True), "light.ceiling_lights": (None, True), "not_supported.not_supported": (None, False), } hass.states.async_set("light.new", "on", {"supported_features": 1}) google_entities = helpers.async_get_entities(hass, config) assert len(google_entities) == 3 assert config.is_supported_cache == { "light.bed_light": (None, True), "light.new": (1, True), "light.ceiling_lights": (None, True), "not_supported.not_supported": (None, False), }
Registry mock setup.
def registries( entity_registry: er.EntityRegistry, device_registry: dr.DeviceRegistry, area_registry: ar.AreaRegistry, ) -> SimpleNamespace: """Registry mock setup.""" ret = SimpleNamespace() ret.entity = entity_registry ret.device = device_registry ret.area = area_registry return ret
Fake a storage for google assistant.
def mock_google_config_store(agent_user_ids=None): """Fake a storage for google assistant.""" store = MagicMock(spec=http.GoogleConfigStore) if agent_user_ids is not None: store.agent_user_ids = agent_user_ids else: store.agent_user_ids = {} return store
Fixture to set the scopes present in the OAuth token.
def mock_scopes() -> list[str]: """Fixture to set the scopes present in the OAuth token.""" return ["https://www.googleapis.com/auth/assistant-sdk-prototype"]
Fixture to set the oauth token expiration time.
def mock_expires_at() -> int: """Fixture to set the oauth token expiration time.""" return time.time() + 3600
Fixture for MockConfigEntry.
def mock_config_entry(expires_at: int, scopes: list[str]) -> MockConfigEntry: """Fixture for MockConfigEntry.""" return MockConfigEntry( domain=DOMAIN, data={ "auth_implementation": DOMAIN, "token": { "access_token": ACCESS_TOKEN, "refresh_token": "mock-refresh-token", "expires_at": expires_at, "scope": " ".join(scopes), }, }, )
Test all supported languages have a default language_code.
def test_default_language_codes(hass: HomeAssistant) -> None: """Test all supported languages have a default language_code.""" for language_code in SUPPORTED_LANGUAGE_CODES: lang = language_code.split("-", maxsplit=1)[0] assert DEFAULT_LANGUAGE_CODES.get(lang)
Test default_language_code.
def test_default_language_code(hass: HomeAssistant) -> None: """Test default_language_code.""" assert default_language_code(hass) == "en-US" hass.config.language = "en" hass.config.country = "US" assert default_language_code(hass) == "en-US" hass.config.language = "en" hass.config.country = "GB" assert default_language_code(hass) == "en-GB" hass.config.language = "en" hass.config.country = "ES" assert default_language_code(hass) == "en-US" hass.config.language = "es" hass.config.country = "ES" assert default_language_code(hass) == "es-ES" hass.config.language = "es" hass.config.country = "MX" assert default_language_code(hass) == "es-MX" hass.config.language = "es" hass.config.country = None assert default_language_code(hass) == "es-ES" hass.config.language = "el" hass.config.country = "GR" assert default_language_code(hass) == "en-US"
Test all supported languages have a mapped broadcast command.
def test_broadcast_language_mapping( hass: HomeAssistant, setup_integration: ComponentSetup ) -> None: """Test all supported languages have a mapped broadcast command.""" for language_code in SUPPORTED_LANGUAGE_CODES: cmds = broadcast_commands(language_code) assert cmds assert len(cmds) == 2 assert cmds[0] assert "{0}" in cmds[0] assert "{1}" not in cmds[0] assert cmds[1] assert "{0}" in cmds[1] assert "{1}" in cmds[1]
Fixture that sets up NamecheapDNS.
def setup_google_domains(hass, aioclient_mock): """Fixture that sets up NamecheapDNS.""" aioclient_mock.get(UPDATE_URL, params={"hostname": DOMAIN}, text="ok 0.0.0.0") hass.loop.run_until_complete( async_setup_component( hass, google_domains.DOMAIN, { "google_domains": { "domain": DOMAIN, "username": USERNAME, "password": PASSWORD, } }, ) )
Mock a config entry.
def mock_config_entry(hass): """Mock a config entry.""" entry = MockConfigEntry( domain="google_generative_ai_conversation", data={ "api_key": "bla", }, ) entry.add_to_hass(hass) return entry
Fixture to set the scopes present in the OAuth token.
def mock_scopes() -> list[str]: """Fixture to set the scopes present in the OAuth token.""" return SCOPES
Fixture to set the oauth token expiration time.
def mock_expires_at() -> int: """Fixture to set the oauth token expiration time.""" return time.time() + 3600
Create Google Mail entry in Home Assistant.
def mock_config_entry(expires_at: int, scopes: list[str]) -> MockConfigEntry: """Create Google Mail entry in Home Assistant.""" return MockConfigEntry( domain=DOMAIN, title=TITLE, unique_id=TITLE, data={ "auth_implementation": DOMAIN, "token": { "access_token": "mock-access-token", "refresh_token": "mock-refresh-token", "expires_at": expires_at, "scope": " ".join(scopes), }, }, )
Mock Google Mail connection.
def mock_connection(aioclient_mock: AiohttpClientMocker) -> None: """Mock Google Mail connection.""" aioclient_mock.post( GOOGLE_TOKEN_URI, json={ "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "type": "Bearer", "expires_in": 60, }, )
Mock the pubsub client.
def mock_client_fixture(): """Mock the pubsub client.""" with mock.patch(f"{GOOGLE_PUBSUB_PATH}.PublisherClient") as client: setattr( client, "from_service_account_json", mock.MagicMock(return_value=mock.MagicMock()), ) yield client
Mock os.path.isfile.
def mock_is_file_fixture(): """Mock os.path.isfile.""" with mock.patch(f"{GOOGLE_PUBSUB_PATH}.os.path.isfile") as is_file: is_file.return_value = True yield is_file
Mock the event bus listener and os component.
def mock_json(hass, monkeypatch): """Mock the event bus listener and os component.""" monkeypatch.setattr( f"{GOOGLE_PUBSUB_PATH}.json.dumps", mock.Mock(return_value=mock.MagicMock()) )
Fixture to set the scopes present in the OAuth token.
def mock_scopes() -> list[str]: """Fixture to set the scopes present in the OAuth token.""" return ["https://www.googleapis.com/auth/drive.file"]
Fixture to set the oauth token expiration time.
def mock_expires_at() -> int: """Fixture to set the oauth token expiration time.""" return time.time() + 3600
Fixture for MockConfigEntry.
def mock_config_entry(expires_at: int, scopes: list[str]) -> MockConfigEntry: """Fixture for MockConfigEntry.""" return MockConfigEntry( domain=DOMAIN, unique_id=TEST_SHEET_ID, data={ "auth_implementation": DOMAIN, "token": { "access_token": "mock-access-token", "refresh_token": "mock-refresh-token", "expires_at": expires_at, "scope": " ".join(scopes), }, }, )
Fixture to specify platforms to test.
def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return []
Fixture to set the oauth token expiration time.
def mock_expires_at() -> int: """Fixture to set the oauth token expiration time.""" return time.time() + 3600
Fixture for OAuth 'token' data for a ConfigEntry.
def mock_token_entry(expires_at: int) -> dict[str, Any]: """Fixture for OAuth 'token' data for a ConfigEntry.""" return { "access_token": FAKE_ACCESS_TOKEN, "refresh_token": FAKE_REFRESH_TOKEN, "scope": " ".join(OAUTH2_SCOPES), "token_type": "Bearer", "expires_at": expires_at, }
Fixture for a config entry.
def mock_config_entry(token_entry: dict[str, Any]) -> MockConfigEntry: """Fixture for a config entry.""" return MockConfigEntry( domain=DOMAIN, unique_id="123", data={ "auth_implementation": DOMAIN, "token": token_entry, }, )
Return a unique user ID.
def user_identifier() -> str: """Return a unique user ID.""" return "123"
Set up userinfo.
def setup_userinfo(user_identifier: str) -> Generator[Mock, None, None]: """Set up userinfo.""" with patch("homeassistant.components.google_tasks.config_flow.build") as mock: mock.return_value.userinfo.return_value.get.return_value.execute.return_value = { "id": user_identifier, "name": "Test Name", } yield mock
Fixture to specify platforms to test.
def platforms() -> list[str]: """Fixture to specify platforms to test.""" return [Platform.TODO]
Fixture for API responses to return during test.
def mock_api_responses() -> list[dict | list]: """Fixture for API responses to return during test.""" return []
Create an http response.
def create_response_object(api_response: dict | list) -> tuple[Response, bytes]: """Create an http response.""" return ( Response({"Content-Type": "application/json"}), json.dumps(api_response).encode(), )
Create a batch response in the multipart/mixed format.
def create_batch_response_object( content_ids: list[str], api_responses: list[dict | list | Response | None] ) -> tuple[Response, bytes]: """Create a batch response in the multipart/mixed format.""" assert len(api_responses) == len(content_ids) content = [] for api_response in api_responses: status = 200 body = "" if isinstance(api_response, Response): status = api_response.status elif api_response is not None: body = json.dumps(api_response) content.extend( [ f"--{BOUNDARY}", "Content-Type: application/http", f"{CONTENT_ID}: {content_ids.pop()}", "", f"HTTP/1.1 {status} OK", "Content-Type: application/json; charset=UTF-8", "", body, ] ) content.append(f"--{BOUNDARY}--") body = ("\r\n".join(content)).encode() return ( Response( { "Content-Type": f"multipart/mixed; boundary={BOUNDARY}", "Content-ID": "1", } ), body, )
Create a fake http2lib response handler that supports generating batch responses. Multi-part response objects are dynamically generated since they need to match the Content-ID of the incoming request.
def create_batch_response_handler( api_responses: list[dict | list | Response | None], ) -> Callable[[Any], tuple[Response, bytes]]: """Create a fake http2lib response handler that supports generating batch responses. Multi-part response objects are dynamically generated since they need to match the Content-ID of the incoming request. """ def _handler(url, method, **kwargs) -> tuple[Response, bytes]: next_api_response = api_responses.pop(0) if method == "POST" and (body := kwargs.get("body")): content_ids = [ line[len(CONTENT_ID) + 2 :] for line in body.splitlines() if line.startswith(f"{CONTENT_ID}:") ] if content_ids: return create_batch_response_object(content_ids, next_api_response) return create_response_object(next_api_response) return _handler
Create a mock http2lib response handler.
def mock_response_handler(api_responses: list[dict | list]) -> list: """Create a mock http2lib response handler.""" return [create_response_object(api_response) for api_response in api_responses]
Fixture to fake out http2lib responses.
def mock_http_response(response_handler: list | Callable) -> Mock: """Fixture to fake out http2lib responses.""" with patch("httplib2.Http.request", side_effect=response_handler) as mock_response: yield mock_response
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.google_translate.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock writing tags.
def tts_mutagen_mock_fixture_autouse(tts_mutagen_mock): """Mock writing tags."""
Mock the TTS cache dir with empty dir.
def mock_tts_cache_dir_autouse(mock_tts_cache_dir): """Mock the TTS cache dir with empty dir.""" return mock_tts_cache_dir
Mock gtts.
def mock_gtts() -> Generator[MagicMock, None, None]: """Mock gtts.""" with patch("homeassistant.components.google_translate.tts.gTTS") as mock_gtts: yield mock_gtts
Return config.
def config_fixture() -> dict[str, Any]: """Return config.""" return {}
Bypass entry setup.
def bypass_setup_fixture(): """Bypass entry setup.""" with patch( "homeassistant.components.google_travel_time.async_setup_entry", return_value=True, ): yield
Bypass platform setup.
def bypass_platform_setup_fixture(): """Bypass platform setup.""" with patch( "homeassistant.components.google_travel_time.sensor.async_setup_entry", return_value=True, ): yield
Return valid config entry.
def validate_config_entry_fixture(): """Return valid config entry.""" with ( patch("homeassistant.components.google_travel_time.helpers.Client"), patch( "homeassistant.components.google_travel_time.helpers.distance_matrix" ) as distance_matrix_mock, ): distance_matrix_mock.return_value = None yield distance_matrix_mock
Return invalid config entry.
def invalidate_config_entry_fixture(validate_config_entry): """Return invalid config entry.""" validate_config_entry.side_effect = ApiError("test")
Throw a REQUEST_DENIED ApiError.
def invalid_api_key_fixture(validate_config_entry): """Throw a REQUEST_DENIED ApiError.""" validate_config_entry.side_effect = ApiError("REQUEST_DENIED", "Invalid API key.")
Throw a Timeout exception.
def timeout_fixture(validate_config_entry): """Throw a Timeout exception.""" validate_config_entry.side_effect = Timeout()
Throw a TransportError exception.
def transport_error_fixture(validate_config_entry): """Throw a TransportError exception.""" validate_config_entry.side_effect = TransportError("Unknown.")
Mock an update to the sensor.
def mock_update_fixture(): """Mock an update to the sensor.""" with ( patch("homeassistant.components.google_travel_time.sensor.Client"), patch( "homeassistant.components.google_travel_time.sensor.distance_matrix" ) as distance_matrix_mock, ): distance_matrix_mock.return_value = { "rows": [ { "elements": [ { "duration_in_traffic": { "value": 1620, "text": "27 mins", }, "duration": { "value": 1560, "text": "26 mins", }, "distance": {"text": "21.3 km"}, } ] } ] } yield distance_matrix_mock
Mock an update to the sensor returning no duration_in_traffic.
def mock_update_duration_fixture(mock_update): """Mock an update to the sensor returning no duration_in_traffic.""" mock_update.return_value = { "rows": [ { "elements": [ { "duration": { "value": 1560, "text": "26 mins", }, "distance": {"text": "21.3 km"}, } ] } ] } return mock_update
Mock an update to the sensor with an empty response.
def mock_update_empty_fixture(mock_update): """Mock an update to the sensor with an empty response.""" mock_update.return_value = None return mock_update
Set up API with fake data.
def setup_api(hass, data, requests_mock): """Set up API with fake data.""" resource = f"http://localhost{google_wifi.ENDPOINT}" now = datetime(1970, month=1, day=1) sensor_dict = {} with patch("homeassistant.util.dt.now", return_value=now): requests_mock.get(resource, text=data, status_code=HTTPStatus.OK) conditions = google_wifi.SENSOR_KEYS api = google_wifi.GoogleWifiAPI("localhost", conditions) for desc in google_wifi.SENSOR_TYPES: sensor_dict[desc.key] = { "sensor": google_wifi.GoogleWifiSensor(api, NAME, desc), "name": f"{NAME}_{desc.key}", "units": desc.native_unit_of_measurement, "icon": desc.icon, } for name in sensor_dict: sensor = sensor_dict[name]["sensor"] sensor.hass = hass return api, sensor_dict
Fake delay to prevent update throttle.
def fake_delay(hass, ha_delay): """Fake delay to prevent update throttle.""" hass_now = dt_util.utcnow() shifted_time = hass_now + timedelta(seconds=ha_delay) async_fire_time_changed(hass, shifted_time)
Test the name.
def test_name(requests_mock: requests_mock.Mocker) -> None: """Test the name.""" api, sensor_dict = setup_api(None, MOCK_DATA, requests_mock) for name in sensor_dict: sensor = sensor_dict[name]["sensor"] test_name = sensor_dict[name]["name"] assert test_name == sensor.name
Test the unit of measurement.
def test_unit_of_measurement( hass: HomeAssistant, requests_mock: requests_mock.Mocker ) -> None: """Test the unit of measurement.""" api, sensor_dict = setup_api(hass, MOCK_DATA, requests_mock) for name in sensor_dict: sensor = sensor_dict[name]["sensor"] assert sensor_dict[name]["units"] == sensor.unit_of_measurement
Test the icon.
def test_icon(requests_mock: requests_mock.Mocker) -> None: """Test the icon.""" api, sensor_dict = setup_api(None, MOCK_DATA, requests_mock) for name in sensor_dict: sensor = sensor_dict[name]["sensor"] assert sensor_dict[name]["icon"] == sensor.icon
Test the initial state.
def test_state(hass: HomeAssistant, requests_mock: requests_mock.Mocker) -> None: """Test the initial state.""" api, sensor_dict = setup_api(hass, MOCK_DATA, requests_mock) now = datetime(1970, month=1, day=1) with patch("homeassistant.util.dt.now", return_value=now): for name in sensor_dict: sensor = sensor_dict[name]["sensor"] fake_delay(hass, 2) sensor.update() if name == google_wifi.ATTR_LAST_RESTART: assert sensor.state == "1969-12-31 00:00:00" elif name == google_wifi.ATTR_UPTIME: assert sensor.state == 1 elif name == google_wifi.ATTR_STATUS: assert sensor.state == "Online" else: assert sensor.state == "initial"
Test state gets updated to unknown when sensor returns no data.
def test_update_when_value_is_none( hass: HomeAssistant, requests_mock: requests_mock.Mocker ) -> None: """Test state gets updated to unknown when sensor returns no data.""" api, sensor_dict = setup_api(hass, None, requests_mock) for name in sensor_dict: sensor = sensor_dict[name]["sensor"] fake_delay(hass, 2) sensor.update() assert sensor.state is None
Test state gets updated when sensor returns a new status.
def test_update_when_value_changed( hass: HomeAssistant, requests_mock: requests_mock.Mocker ) -> None: """Test state gets updated when sensor returns a new status.""" api, sensor_dict = setup_api(hass, MOCK_DATA_NEXT, requests_mock) now = datetime(1970, month=1, day=1) with patch("homeassistant.util.dt.now", return_value=now): for name in sensor_dict: sensor = sensor_dict[name]["sensor"] fake_delay(hass, 2) sensor.update() if name == google_wifi.ATTR_LAST_RESTART: assert sensor.state == "1969-12-30 00:00:00" elif name == google_wifi.ATTR_UPTIME: assert sensor.state == 2 elif name == google_wifi.ATTR_STATUS: assert sensor.state == "Offline" elif name == google_wifi.ATTR_NEW_VERSION: assert sensor.state == "Latest" elif name == google_wifi.ATTR_LOCAL_IP: assert sensor.state is None else: assert sensor.state == "next"
Test state logs an error when data is missing.
def test_when_api_data_missing( hass: HomeAssistant, requests_mock: requests_mock.Mocker ) -> None: """Test state logs an error when data is missing.""" api, sensor_dict = setup_api(hass, MOCK_DATA_MISSING, requests_mock) now = datetime(1970, month=1, day=1) with patch("homeassistant.util.dt.now", return_value=now): for name in sensor_dict: sensor = sensor_dict[name]["sensor"] fake_delay(hass, 2) sensor.update() assert sensor.state is None
Test state updates when Google Wifi unavailable.
def test_update_when_unavailable( hass: HomeAssistant, requests_mock: requests_mock.Mocker ) -> None: """Test state updates when Google Wifi unavailable.""" api, sensor_dict = setup_api(hass, None, requests_mock) api.update = Mock( "google_wifi.GoogleWifiAPI.update", side_effect=update_side_effect(hass, requests_mock), ) for name in sensor_dict: sensor = sensor_dict[name]["sensor"] sensor.update() assert sensor.state is None
Mock representation of update function.
def update_side_effect(hass, requests_mock): """Mock representation of update function.""" api, sensor_dict = setup_api(hass, MOCK_DATA, requests_mock) api.data = None api.available = False
Auto mock bluetooth.
def mock_bluetooth(enable_bluetooth): """Auto mock bluetooth."""
Set up Govee Local API fixture.
def fixture_mock_govee_api(): """Set up Govee Local API fixture.""" mock_api = AsyncMock(spec=GoveeController) mock_api.start = AsyncMock() mock_api.turn_on_off = AsyncMock() mock_api.set_brightness = AsyncMock() mock_api.set_color = AsyncMock() mock_api._async_update_data = AsyncMock() return mock_api
Override async_setup_entry.
def fixture_mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.govee_light_local.async_setup_entry", return_value=True, ) as mock_setup_entry: yield mock_setup_entry
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.gpsd.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Mock device tracker config loading.
def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading."""
Mock Graphite Feeder fixture.
def fixture_mock_gf(): """Mock Graphite Feeder fixture.""" with patch("homeassistant.components.graphite.GraphiteFeeder") as mock_gf: yield mock_gf
Mock socket fixture.
def fixture_mock_socket(): """Mock socket fixture.""" with patch("socket.socket") as mock_socket: yield mock_socket
Mock time fixture.
def fixture_mock_time(): """Mock time fixture.""" with patch("time.time") as mock_time: yield mock_time
Build mock device info structure.
def build_device_info_mock( name="fake-device-1", ipAddress="1.1.1.1", mac="aabbcc112233" ): """Build mock device info structure.""" mock = Mock(ip=ipAddress, port=7000, mac=mac) mock.name = name return mock
Build mock device object.
def build_device_mock(name="fake-device-1", ipAddress="1.1.1.1", mac="aabbcc112233"): """Build mock device object.""" return Mock( device_info=build_device_info_mock(name, ipAddress, mac), name=name, bind=AsyncMock(), update_state=AsyncMock(), push_state_update=AsyncMock(), temperature_units=0, mode=0, fan_speed=0, horizontal_swing=0, vertical_swing=0, target_temperature=25, current_temperature=25, power=False, sleep=False, quiet=False, turbo=False, power_save=False, steady_heat=False, )
Override async_setup_entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Override async_setup_entry.""" with patch( "homeassistant.components.gree.async_setup_entry", return_value=True ) as mock_setup_entry: yield mock_setup_entry
Patch the discovery object.
def discovery_fixture(): """Patch the discovery object.""" with patch("homeassistant.components.gree.bridge.Discovery") as mock: mock.return_value = FakeDiscovery() yield mock
Patch the device search and bind.
def device_fixture(): """Patch the device search and bind.""" with patch( "homeassistant.components.gree.bridge.Device", return_value=build_device_mock(), ) as mock: yield mock
Fixture for dtutil.now.
def mock_now(): """Fixture for dtutil.now.""" return dt_util.utcnow()
Fixture for dtutil.now.
def mock_now(): """Fixture for dtutil.now.""" return dt_util.utcnow()
Wrap the given sensor config in the boilerplate for a single monitor with serial number SINGLE_MONITOR_SERIAL_NUMBER.
def make_single_monitor_config_with_sensors(sensors: dict[str, Any]) -> dict[str, Any]: """Wrap the given sensor config in the boilerplate for a single monitor with serial number SINGLE_MONITOR_SERIAL_NUMBER.""" return { DOMAIN: { CONF_PORT: 7513, CONF_MONITORS: [ { CONF_SERIAL_NUMBER: f"00{SINGLE_MONITOR_SERIAL_NUMBER}", **sensors, } ], } }
Create a MagicMock with methods that follow the same pattern for working with listeners in the greeneye_monitor API.
def mock_with_listeners() -> MagicMock: """Create a MagicMock with methods that follow the same pattern for working with listeners in the greeneye_monitor API.""" mock = MagicMock() add_listeners(mock) return mock
Create an AsyncMock with methods that follow the same pattern for working with listeners in the greeneye_monitor API.
def async_mock_with_listeners() -> AsyncMock: """Create an AsyncMock with methods that follow the same pattern for working with listeners in the greeneye_monitor API.""" mock = AsyncMock() add_listeners(mock) return mock
Add add_listener and remove_listener methods to the given mock that behave like their counterparts on objects from the greeneye_monitor API, plus a notify_all_listeners method that calls all registered listeners.
def add_listeners(mock: MagicMock | AsyncMock) -> None: """Add add_listener and remove_listener methods to the given mock that behave like their counterparts on objects from the greeneye_monitor API, plus a notify_all_listeners method that calls all registered listeners.""" mock.listeners = [] mock.add_listener = mock.listeners.append mock.remove_listener = mock.listeners.remove def notify_all_listeners(*args): for listener in list(mock.listeners): listener(*args) mock.notify_all_listeners = notify_all_listeners
Create a mock GreenEye Monitor pulse counter.
def mock_pulse_counter() -> MagicMock: """Create a mock GreenEye Monitor pulse counter.""" pulse_counter = mock_with_listeners() pulse_counter.pulses = 1000 pulse_counter.pulses_per_second = 10 return pulse_counter
Create a mock GreenEye Monitor temperature sensor.
def mock_temperature_sensor() -> MagicMock: """Create a mock GreenEye Monitor temperature sensor.""" temperature_sensor = mock_with_listeners() temperature_sensor.temperature = 32.0 return temperature_sensor
Create a mock GreenEye Monitor voltage sensor.
def mock_voltage_sensor() -> MagicMock: """Create a mock GreenEye Monitor voltage sensor.""" voltage_sensor = mock_with_listeners() voltage_sensor.voltage = 120.0 return voltage_sensor
Create a mock GreenEye Monitor CT channel.
def mock_channel() -> MagicMock: """Create a mock GreenEye Monitor CT channel.""" channel = mock_with_listeners() channel.absolute_watt_seconds = 1000 channel.polarized_watt_seconds = -400 channel.watts = None return channel