response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Load payload for playqueue 1234 and return it.
def playqueue_1234_fixture(): """Load payload for playqueue 1234 and return it.""" return load_fixture("plex/playqueue_1234.xml")
Load payload accounts on the Plex server and return it.
def plex_server_accounts_fixture(): """Load payload accounts on the Plex server and return it.""" return load_fixture("plex/plex_server_accounts.xml")
Load base payload for Plex server info and return it.
def plex_server_base_fixture(): """Load base payload for Plex server info and return it.""" return load_fixture("plex/plex_server_base.xml")
Load default payload for Plex server info and return it.
def plex_server_default_fixture(plex_server_base): """Load default payload for Plex server info and return it.""" return plex_server_base.format( name="Plex Server 1", machine_identifier="unique_id_123" )
Load available clients payload for Plex server and return it.
def plex_server_clients_fixture(): """Load available clients payload for Plex server and return it.""" return load_fixture("plex/plex_server_clients.xml")
Load account info from plex.tv and return it.
def plextv_account_fixture(): """Load account info from plex.tv and return it.""" return load_fixture("plex/plextv_account.xml")
Load single-server payload for plex.tv resources and return it.
def plextv_resources_fixture(): """Load single-server payload for plex.tv resources and return it.""" return load_fixture("plex/plextv_resources_one_server.xml")
Load two-server payload for plex.tv resources and return it.
def plextv_resources_two_servers_fixture(): """Load two-server payload for plex.tv resources and return it.""" return load_fixture("plex/plextv_resources_two_servers.xml")
Load payload for plex.tv shared users and return it.
def plextv_shared_users_fixture(): """Load payload for plex.tv shared users and return it.""" return load_fixture("plex/plextv_shared_users.xml")
Load the base session payload and return it.
def session_base_fixture(): """Load the base session payload and return it.""" return load_fixture("plex/session_base.xml")
Load the default session payload and return it.
def session_default_fixture(session_base): """Load the default session payload and return it.""" return session_base.format(user_id=1)
Load the new user session payload and return it.
def session_new_user_fixture(session_base): """Load the new user session payload and return it.""" return session_base.format(user_id=1001)
Load a photo session payload and return it.
def session_photo_fixture(): """Load a photo session payload and return it.""" return load_fixture("plex/session_photo.xml")
Load a Plex Web session payload and return it.
def session_plexweb_fixture(): """Load a Plex Web session payload and return it.""" return load_fixture("plex/session_plexweb.xml")
Load a transient session payload and return it.
def session_transient_fixture(): """Load a transient session payload and return it.""" return load_fixture("plex/session_transient.xml")
Load a hypothetical unknown session payload and return it.
def session_unknown_fixture(): """Load a hypothetical unknown session payload and return it.""" return load_fixture("plex/session_unknown.xml")
Load a Live TV session payload and return it.
def session_live_tv_fixture(): """Load a Live TV session payload and return it.""" return load_fixture("plex/session_live_tv.xml")
Load livetv/sessions payload and return it.
def livetv_sessions_fixture(): """Load livetv/sessions payload and return it.""" return load_fixture("plex/livetv_sessions.xml")
Load a security token payload and return it.
def security_token_fixture(): """Load a security token payload and return it.""" return load_fixture("plex/security_token.xml")
Load a show's seasons payload and return it.
def show_seasons_fixture(): """Load a show's seasons payload and return it.""" return load_fixture("plex/show_seasons.xml")
Load Sonos resources payload and return it.
def sonos_resources_fixture(): """Load Sonos resources payload and return it.""" return load_fixture("plex/sonos_resources.xml")
Load hubs resource payload and return it.
def hubs_fixture(): """Load hubs resource payload and return it.""" return load_fixture("plex/hubs.xml")
Load music library hubs resource payload and return it.
def hubs_music_library_fixture(): """Load music library hubs resource payload and return it.""" return load_fixture("plex/hubs_library_section.xml")
Load a no-change update resource payload and return it.
def update_check_fixture_nochange() -> str: """Load a no-change update resource payload and return it.""" return load_fixture("plex/release_nochange.xml")
Load a changed update resource payload and return it.
def update_check_fixture_new() -> str: """Load a changed update resource payload and return it.""" return load_fixture("plex/release_new.xml")
Load a changed update resource payload (not updatable) and return it.
def update_check_fixture_new_not_updatable() -> str: """Load a changed update resource payload (not updatable) and return it.""" return load_fixture("plex/release_new_not_updatable.xml")
Mock the PlexWebsocket class.
def mock_websocket(): """Mock the PlexWebsocket class.""" with patch("homeassistant.components.plex.PlexWebsocket", autospec=True) as ws: yield ws
Mock Plex API calls.
def mock_plex_calls( entry, requests_mock, children_20, children_30, children_200, children_300, empty_library, empty_payload, grandchildren_300, library, library_sections, library_movies_all, library_movies_collections, library_movies_metadata, library_movies_sort, library_music_all, library_music_collections, library_music_metadata, library_music_sort, library_tvshows_all, library_tvshows_collections, library_tvshows_metadata, library_tvshows_sort, media_1, media_30, media_100, media_200, playlists, playlist_500, plextv_account, plextv_resources, plextv_shared_users, plex_server_accounts, plex_server_clients, plex_server_default, security_token, update_check_nochange, ): """Mock Plex API calls.""" requests_mock.get("https://plex.tv/api/users/", text=plextv_shared_users) requests_mock.get("https://plex.tv/api/invites/requested", text=empty_payload) requests_mock.get("https://plex.tv/api/v2/user", text=plextv_account) requests_mock.get("https://plex.tv/api/v2/resources", text=plextv_resources) url = plex_server_url(entry) for server in [url, PLEX_DIRECT_URL]: requests_mock.get(server, text=plex_server_default) requests_mock.get(f"{server}/accounts", text=plex_server_accounts) requests_mock.get(f"{url}/clients", text=plex_server_clients) requests_mock.get(f"{url}/library", text=library) requests_mock.get(f"{url}/library/sections", text=library_sections) requests_mock.get(f"{url}/library/onDeck", text=empty_library) requests_mock.get(f"{url}/library/sections/1/sorts", text=library_movies_sort) requests_mock.get(f"{url}/library/sections/2/sorts", text=library_tvshows_sort) requests_mock.get(f"{url}/library/sections/3/sorts", text=library_music_sort) requests_mock.get(f"{url}/library/sections/1/all", text=library_movies_all) requests_mock.get(f"{url}/library/sections/2/all", text=library_tvshows_all) requests_mock.get(f"{url}/library/sections/3/all", text=library_music_all) requests_mock.get( f"{url}/library/sections/1/all?includeMeta=1&includeAdvanced=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0", text=library_movies_metadata, ) requests_mock.get( f"{url}/library/sections/2/all?includeMeta=1&includeAdvanced=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0", text=library_tvshows_metadata, ) requests_mock.get( f"{url}/library/sections/3/all?includeMeta=1&includeAdvanced=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0", text=library_music_metadata, ) requests_mock.get( f"{url}/library/sections/1/collections?includeMeta=1&includeAdvanced=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0", text=library_movies_collections, ) requests_mock.get( f"{url}/library/sections/2/collections?includeMeta=1&includeAdvanced=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0", text=library_tvshows_collections, ) requests_mock.get( f"{url}/library/sections/3/collections?includeMeta=1&includeAdvanced=1&X-Plex-Container-Start=0&X-Plex-Container-Size=0", text=library_music_collections, ) requests_mock.get(f"{url}/library/metadata/200/children", text=children_200) requests_mock.get(f"{url}/library/metadata/300/children", text=children_300) requests_mock.get(f"{url}/library/metadata/300/allLeaves", text=grandchildren_300) requests_mock.get(f"{url}/library/metadata/1", text=media_1) requests_mock.get(f"{url}/library/metadata/30", text=media_30) requests_mock.get(f"{url}/library/metadata/100", text=media_100) requests_mock.get(f"{url}/library/metadata/200", text=media_200) requests_mock.get(f"{url}/library/metadata/20/children", text=children_20) requests_mock.get(f"{url}/library/metadata/30/children", text=children_30) requests_mock.get(f"{url}/playlists", text=playlists) requests_mock.get(f"{url}/playlists/500/items", text=playlist_500) requests_mock.get(f"{url}/security/token", text=security_token) requests_mock.put(f"{url}/updater/check") requests_mock.get(f"{url}/updater/status", text=update_check_nochange)
Set up and return a mocked Plex server instance.
def setup_plex_server( hass, entry, livetv_sessions, mock_websocket, mock_plex_calls, requests_mock, empty_payload, session_default, session_live_tv, session_photo, session_plexweb, session_transient, session_unknown, ): """Set up and return a mocked Plex server instance.""" async def _wrapper(**kwargs): """Wrap the fixture to allow passing arguments to the setup method.""" url = plex_server_url(entry) config_entry = kwargs.get("config_entry", entry) disable_clients = kwargs.pop("disable_clients", False) disable_gdm = kwargs.pop("disable_gdm", True) client_type = kwargs.pop("client_type", None) session_type = kwargs.pop("session_type", None) if client_type == "plexweb": session = session_plexweb elif session_type == "photo": session = session_photo elif session_type == "live_tv": session = session_live_tv requests_mock.get(f"{url}/livetv/sessions/live_tv_1", text=livetv_sessions) elif session_type == "transient": session = session_transient elif session_type == "unknown": session = session_unknown else: session = session_default requests_mock.get(f"{url}/status/sessions", text=session) if disable_clients: requests_mock.get(f"{url}/clients", text=empty_payload) with patch( "homeassistant.components.plex.GDM", return_value=MockGDM(disabled=disable_gdm), ): config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() websocket_connected(mock_websocket) await hass.async_block_till_done() return hass.data[DOMAIN][SERVERS][entry.unique_id] return _wrapper
Call the websocket callback method to signal successful connection.
def websocket_connected(mock_websocket): """Call the websocket callback method to signal successful connection.""" callback = mock_websocket.call_args[0][1] callback(SIGNAL_CONNECTION_STATE, STATE_CONNECTED, None)
Call the websocket callback method with a Plex update.
def trigger_plex_update(mock_websocket, msgtype="playing", payload=UPDATE_PAYLOAD): """Call the websocket callback method with a Plex update.""" callback = mock_websocket.call_args[0][1] callback(msgtype, payload, None)
Undecode the json data.
def _read_json(environment: str, call: str) -> dict[str, Any]: """Undecode the json data.""" fixture = load_fixture(f"plugwise/{environment}/{call}.json") return json.loads(fixture)
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="My Plugwise", domain=DOMAIN, data={ CONF_HOST: "127.0.0.1", CONF_MAC: "AA:BB:CC:DD:EE:FF", CONF_PASSWORD: "test-password", CONF_PORT: 80, CONF_USERNAME: "smile", }, unique_id="smile98765", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[AsyncMock, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.plugwise.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Return a mocked Smile client.
def mock_smile_config_flow() -> Generator[None, MagicMock, None]: """Return a mocked Smile client.""" with patch( "homeassistant.components.plugwise.config_flow.Smile", autospec=True, ) as smile_mock: smile = smile_mock.return_value smile.smile_hostname = "smile12345" smile.smile_model = "Test Model" smile.smile_name = "Test Smile Name" smile.connect.return_value = True yield smile
Create a Mock Adam environment for testing exceptions.
def mock_smile_adam() -> Generator[None, MagicMock, None]: """Create a Mock Adam environment for testing exceptions.""" chosen_env = "adam_multiple_devices_per_zone" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "fe799307f1624099878210aa0b9f1475" smile.heater_id = "90986d591dcd426cae3ec3e8111ff730" smile.smile_version = "3.0.15" smile.smile_type = "thermostat" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Adam" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a 2nd Mock Adam environment for testing exceptions.
def mock_smile_adam_2() -> Generator[None, MagicMock, None]: """Create a 2nd Mock Adam environment for testing exceptions.""" chosen_env = "m_adam_heating" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "da224107914542988a88561b4452b0f6" smile.heater_id = "056ee145a816487eaa69243c3280f8bf" smile.smile_version = "3.6.4" smile.smile_type = "thermostat" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Adam" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a 3rd Mock Adam environment for testing exceptions.
def mock_smile_adam_3() -> Generator[None, MagicMock, None]: """Create a 3rd Mock Adam environment for testing exceptions.""" chosen_env = "m_adam_cooling" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "da224107914542988a88561b4452b0f6" smile.heater_id = "056ee145a816487eaa69243c3280f8bf" smile.smile_version = "3.6.4" smile.smile_type = "thermostat" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Adam" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a 4th Mock Adam environment for testing exceptions.
def mock_smile_adam_4() -> Generator[None, MagicMock, None]: """Create a 4th Mock Adam environment for testing exceptions.""" chosen_env = "m_adam_jip" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "b5c2386c6f6342669e50fe49dd05b188" smile.heater_id = "e4684553153b44afbef2200885f379dc" smile.smile_version = "3.2.8" smile.smile_type = "thermostat" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Adam" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a Mock Anna environment for testing exceptions.
def mock_smile_anna() -> Generator[None, MagicMock, None]: """Create a Mock Anna environment for testing exceptions.""" chosen_env = "anna_heatpump_heating" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "015ae9ea3f964e668e490fa39da3870b" smile.heater_id = "1cbf783bb11e4a7c8a6843dee3a86927" smile.smile_version = "4.0.15" smile.smile_type = "thermostat" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Smile Anna" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a 2nd Mock Anna environment for testing exceptions.
def mock_smile_anna_2() -> Generator[None, MagicMock, None]: """Create a 2nd Mock Anna environment for testing exceptions.""" chosen_env = "m_anna_heatpump_cooling" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "015ae9ea3f964e668e490fa39da3870b" smile.heater_id = "1cbf783bb11e4a7c8a6843dee3a86927" smile.smile_version = "4.0.15" smile.smile_type = "thermostat" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Smile Anna" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a 3rd Mock Anna environment for testing exceptions.
def mock_smile_anna_3() -> Generator[None, MagicMock, None]: """Create a 3rd Mock Anna environment for testing exceptions.""" chosen_env = "m_anna_heatpump_idle" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "015ae9ea3f964e668e490fa39da3870b" smile.heater_id = "1cbf783bb11e4a7c8a6843dee3a86927" smile.smile_version = "4.0.15" smile.smile_type = "thermostat" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Smile Anna" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a Mock P1 DSMR environment for testing exceptions.
def mock_smile_p1() -> Generator[None, MagicMock, None]: """Create a Mock P1 DSMR environment for testing exceptions.""" chosen_env = "p1v4_442_single" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "a455b61e52394b2db5081ce025a430f3" smile.heater_id = None smile.smile_version = "4.4.2" smile.smile_type = "power" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Smile P1" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a Mock P1 3-phase DSMR environment for testing exceptions.
def mock_smile_p1_2() -> Generator[None, MagicMock, None]: """Create a Mock P1 3-phase DSMR environment for testing exceptions.""" chosen_env = "p1v4_442_triple" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "03e65b16e4b247a29ae0d75a78cb492e" smile.heater_id = None smile.smile_version = "4.4.2" smile.smile_type = "power" smile.smile_hostname = "smile98765" smile.smile_model = "Gateway" smile.smile_name = "Smile P1" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a Mock Stretch environment for testing exceptions.
def mock_stretch() -> Generator[None, MagicMock, None]: """Create a Mock Stretch environment for testing exceptions.""" chosen_env = "stretch_v31" with patch( "homeassistant.components.plugwise.coordinator.Smile", autospec=True ) as smile_mock: smile = smile_mock.return_value smile.gateway_id = "259882df3c05415b99c2d962534ce820" smile.heater_id = None smile.smile_version = "3.1.11" smile.smile_type = "stretch" smile.smile_hostname = "stretch98765" smile.smile_model = "Gateway" smile.smile_name = "Stretch" smile.connect.return_value = True all_data = _read_json(chosen_env, "all_data") smile.async_update.return_value = PlugwiseData( all_data["gateway"], all_data["devices"] ) yield smile
Create a Mock Smile for testing exceptions.
def mock_smile(): """Create a Mock Smile for testing exceptions.""" with patch( "homeassistant.components.plugwise.config_flow.Smile", ) as smile_mock: smile_mock.ConnectionFailedError = ConnectionFailedError smile_mock.InvalidAuthentication = InvalidAuthentication smile_mock.InvalidSetupError = InvalidSetupError smile_mock.InvalidXMLError = InvalidXMLError smile_mock.ResponseError = ResponseError smile_mock.UnsupportedDeviceError = UnsupportedDeviceError smile_mock.return_value.connect.return_value = True yield smile_mock.return_value
Init a configuration flow.
def init_config_flow(hass, side_effect=None): """Init a configuration flow.""" config_flow.register_flow_implementation(hass, DOMAIN, "id", "secret") flow = config_flow.PointFlowHandler() flow._get_authorization_url = AsyncMock( return_value="https://example.com", side_effect=side_effect ) flow.hass = hass return flow
Set PointSession authorized.
def is_authorized(): """Set PointSession authorized.""" return True
Mock pypoint.
def mock_pypoint(is_authorized): """Mock pypoint.""" with patch( "homeassistant.components.point.config_flow.PointSession" ) as PointSession: PointSession.return_value.get_access_token = AsyncMock( return_value={"access_token": "boo"} ) PointSession.return_value.is_authorized = is_authorized PointSession.return_value.user = AsyncMock( return_value={"email": "[email protected]"} ) yield PointSession
Assert that a flow returned a form error.
def assert_form_error(result: FlowResult, key: str, value: str) -> None: """Assert that a flow returned a form error.""" assert result["type"] is FlowResultType.FORM assert result["errors"] assert result["errors"][key] == value
Set the state of an entity with an Entity Registry entry.
def set_state_with_entry( hass: HomeAssistant, entry: er.RegistryEntry, state, additional_attributes=None, new_entity_id=None, ): """Set the state of an entity with an Entity Registry entry.""" attributes = {} if entry.original_name: attributes[ATTR_FRIENDLY_NAME] = entry.original_name if entry.unit_of_measurement: attributes[ATTR_UNIT_OF_MEASUREMENT] = entry.unit_of_measurement if entry.original_device_class: attributes[ATTR_DEVICE_CLASS] = entry.original_device_class if additional_attributes: attributes = {**attributes, **additional_attributes} hass.states.async_set( entity_id=new_entity_id if new_entity_id else entry.entity_id, new_state=state, attributes=attributes, )
Mock the prometheus client.
def mock_client_fixture(): """Mock the prometheus client.""" with mock.patch(f"{PROMETHEUS_PATH}.prometheus_client") as client: counter_client = mock.MagicMock() client.Counter = mock.MagicMock(return_value=counter_client) setattr(counter_client, "labels", mock.MagicMock(return_value=mock.MagicMock())) yield counter_client
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( domain=PROSEGUR_DOMAIN, data={ "contract": CONTRACT, CONF_USERNAME: "[email protected]", CONF_PASSWORD: "password", "country": "PT", }, )
Return list of contracts per user.
def mock_list_contracts() -> AsyncMock: """Return list of contracts per user.""" return [ {"contractId": "123", "description": "a b c"}, {"contractId": "456", "description": "x y z"}, ]
Return the mocked alarm install.
def mock_install() -> AsyncMock: """Return the mocked alarm install.""" install = MagicMock() install.contract = CONTRACT install.cameras = [Camera("1", "test_cam")] install.arm = AsyncMock() install.disarm = AsyncMock() install.arm_partially = AsyncMock() install.get_image = AsyncMock(return_value=b"ABC") install.request_image = AsyncMock() install.data = {"contract": CONTRACT} install.activity = AsyncMock(return_value={"event": "armed"}) return install
Setups authentication.
def mock_auth(): """Setups authentication.""" with patch("pyprosegur.auth.Auth.login", return_value=True): yield
Mock the status of the alarm.
def mock_status(request): """Mock the status of the alarm.""" install = AsyncMock() install.contract = CONTRACT install.status = request.param with patch("pyprosegur.installation.Installation.retrieve", return_value=install): yield
Set up zones for test.
def config_zones(hass: HomeAssistant): """Set up zones for test.""" hass.config.components.add("zone") hass.states.async_set( "zone.home", "zoning", {"name": "Home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, ) hass.states.async_set( "zone.work", "zoning", {"name": "Work", "latitude": 2.3, "longitude": 1.3, "radius": 10}, )
Mock a PrusaLink config entry.
def mock_config_entry(hass): """Mock a PrusaLink config entry.""" entry = MockConfigEntry( domain=DOMAIN, data={"host": "http://example.com", "username": "dummy", "password": "dummypw"}, version=1, minor_version=2, ) entry.add_to_hass(hass) return entry
Mock PrusaLink version API.
def mock_version_api(hass): """Mock PrusaLink version API.""" resp = { "api": "2.0.0", "server": "2.1.2", "text": "PrusaLink", "hostname": "PrusaXL", } with patch("pyprusalink.PrusaLink.get_version", return_value=resp): yield resp
Mock PrusaLink info API.
def mock_info_api(hass): """Mock PrusaLink info API.""" resp = { "nozzle_diameter": 0.40, "mmu": False, "serial": "serial-1337", "hostname": "PrusaXL", "min_extrusion_temp": 170, } with patch("pyprusalink.PrusaLink.get_info", return_value=resp): yield resp
Mock PrusaLink printer API.
def mock_get_legacy_printer(hass): """Mock PrusaLink printer API.""" resp = {"telemetry": {"material": "PLA"}} with patch("pyprusalink.PrusaLink.get_legacy_printer", return_value=resp): yield resp
Mock PrusaLink printer API.
def mock_get_status_idle(hass): """Mock PrusaLink printer API.""" resp = { "storage": { "path": "/usb/", "name": "usb", "read_only": False, }, "printer": { "state": "IDLE", "temp_bed": 41.9, "target_bed": 60.5, "temp_nozzle": 47.8, "target_nozzle": 210.1, "axis_z": 1.8, "axis_x": 7.9, "axis_y": 8.4, "flow": 100, "speed": 100, "fan_hotend": 100, "fan_print": 75, }, } with patch("pyprusalink.PrusaLink.get_status", return_value=resp): yield resp
Mock PrusaLink printer API.
def mock_get_status_printing(hass): """Mock PrusaLink printer API.""" resp = { "job": { "id": 129, "progress": 37.00, "time_remaining": 73020, "time_printing": 43987, }, "storage": {"path": "/usb/", "name": "usb", "read_only": False}, "printer": { "state": "PRINTING", "temp_bed": 53.9, "target_bed": 85.0, "temp_nozzle": 6.0, "target_nozzle": 0.0, "axis_z": 5.0, "flow": 100, "speed": 100, "fan_hotend": 5000, "fan_print": 2500, }, } with patch("pyprusalink.PrusaLink.get_status", return_value=resp): yield resp
Mock PrusaLink job API having no job.
def mock_job_api_idle(hass): """Mock PrusaLink job API having no job.""" resp = {} with patch("pyprusalink.PrusaLink.get_job", return_value=resp): yield resp
Mock PrusaLink job API having a job with idle state (MK3).
def mock_job_api_idle_mk3(hass): """Mock PrusaLink job API having a job with idle state (MK3).""" resp = { "id": 129, "state": "IDLE", "progress": 0.0, "time_remaining": None, "time_printing": 0, "file": { "refs": { "icon": "/thumb/s/usb/TabletStand3~4.BGC", "thumbnail": "/thumb/l/usb/TabletStand3~4.BGC", "download": "/usb/TabletStand3~4.BGC", }, "name": "TabletStand3~4.BGC", "display_name": "TabletStand3.bgcode", "path": "/usb", "size": 754535, "m_timestamp": 1698686881, }, } with patch("pyprusalink.PrusaLink.get_job", return_value=resp): yield resp
Mock PrusaLink printing.
def mock_job_api_printing(hass): """Mock PrusaLink printing.""" resp = { "id": 129, "state": "PRINTING", "progress": 37.00, "time_remaining": 73020, "time_printing": 43987, "file": { "refs": { "icon": "/thumb/s/usb/TabletStand3~4.BGC", "thumbnail": "/thumb/l/usb/TabletStand3~4.BGC", "download": "/usb/TabletStand3~4.BGC", }, "name": "TabletStand3~4.BGC", "display_name": "TabletStand3.bgcode", "path": "/usb", "size": 754535, "m_timestamp": 1698686881, }, } with patch("pyprusalink.PrusaLink.get_job", return_value=resp): yield resp
Mock PrusaLink paused printing.
def mock_job_api_paused(hass, mock_get_status_printing, mock_job_api_printing): """Mock PrusaLink paused printing.""" mock_job_api_printing["state"] = "PAUSED" mock_get_status_printing["printer"]["state"] = "PAUSED"
Mock PrusaLink API.
def mock_api( mock_version_api, mock_info_api, mock_get_legacy_printer, mock_get_status_idle, mock_job_api_idle, ): """Mock PrusaLink API."""
Only setup button platform.
def setup_button_platform_only(): """Only setup button platform.""" with patch("homeassistant.components.prusalink.PLATFORMS", [Platform.BUTTON]): yield
Only setup camera platform.
def setup_camera_platform_only(): """Only setup camera platform.""" with patch("homeassistant.components.prusalink.PLATFORMS", [Platform.CAMERA]): yield
Only setup sensor platform.
def setup_sensor_platform_only(): """Only setup sensor platform.""" with ( patch("homeassistant.components.prusalink.PLATFORMS", [Platform.SENSOR]), patch( "homeassistant.helpers.entity.Entity.entity_registry_enabled_default", PropertyMock(return_value=True), ), ): yield
Prevent load JSON being used.
def patch_load_json_object() -> Generator[MagicMock, None, None]: """Prevent load JSON being used.""" with patch( "homeassistant.components.ps4.load_json_object", return_value={} ) as mock_load: yield mock_load
Prevent save JSON being used.
def patch_save_json() -> Generator[MagicMock, None, None]: """Prevent save JSON being used.""" with patch("homeassistant.components.ps4.save_json") as mock_save: yield mock_save
Prevent save JSON being used.
def patch_get_status() -> Generator[MagicMock, None, None]: """Prevent save JSON being used.""" with patch("pyps4_2ndscreen.ps4.get_status", return_value=None) as mock_get_status: yield mock_get_status
Mock pyps4_2ndscreen.ddp.async_create_ddp_endpoint.
def mock_ddp_endpoint() -> Generator[None, None, None]: """Mock pyps4_2ndscreen.ddp.async_create_ddp_endpoint.""" protocol = DDPProtocol() protocol._local_port = DEFAULT_UDP_PORT protocol._transport = MagicMock() with patch( "homeassistant.components.ps4.async_create_ddp_endpoint", return_value=(None, protocol), ): yield
Prevent PS4 doing I/O.
def patch_io( patch_load_json_object: MagicMock, patch_save_json: MagicMock, patch_get_status: MagicMock, mock_ddp_endpoint: None, ) -> None: """Prevent PS4 doing I/O."""
Mock location info.
def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield
Patch ps4 setup entry.
def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield
Test old data format is converted to new format.
def test_games_reformat_to_dict( hass: HomeAssistant, patch_load_json_object: MagicMock ) -> None: """Test old data format is converted to new format.""" patch_load_json_object.return_value = MOCK_GAMES_DATA_OLD_STR_FORMAT with ( patch("homeassistant.components.ps4.save_json", side_effect=MagicMock()), patch("os.path.isfile", return_value=True), ): mock_games = ps4.load_games(hass, MOCK_ENTRY_ID) # New format is a nested dict. assert isinstance(mock_games, dict) assert mock_games["mock_id"][ATTR_MEDIA_TITLE] == "mock_title" assert mock_games["mock_id2"][ATTR_MEDIA_TITLE] == "mock_title2" for mock_game in mock_games: mock_data = mock_games[mock_game] assert isinstance(mock_data, dict) assert mock_data assert mock_data[ATTR_MEDIA_IMAGE_URL] is None assert mock_data[ATTR_LOCKED] is False assert mock_data[ATTR_MEDIA_CONTENT_TYPE] == MediaType.GAME
Test that games are loaded correctly.
def test_load_games(hass: HomeAssistant, patch_load_json_object: MagicMock) -> None: """Test that games are loaded correctly.""" patch_load_json_object.return_value = MOCK_GAMES with ( patch("homeassistant.components.ps4.save_json", side_effect=MagicMock()), patch("os.path.isfile", return_value=True), ): mock_games = ps4.load_games(hass, MOCK_ENTRY_ID) assert isinstance(mock_games, dict) mock_data = mock_games[MOCK_ID] assert isinstance(mock_data, dict) assert mock_data[ATTR_MEDIA_TITLE] == MOCK_TITLE assert mock_data[ATTR_MEDIA_IMAGE_URL] == MOCK_URL assert mock_data[ATTR_LOCKED] is False assert mock_data[ATTR_MEDIA_CONTENT_TYPE] == MediaType.GAME
Test that loading games always returns a dict.
def test_loading_games_returns_dict( hass: HomeAssistant, patch_load_json_object: MagicMock ) -> None: """Test that loading games always returns a dict.""" patch_load_json_object.side_effect = HomeAssistantError with ( patch("homeassistant.components.ps4.save_json", side_effect=MagicMock()), patch("os.path.isfile", return_value=True), ): mock_games = ps4.load_games(hass, MOCK_ENTRY_ID) assert isinstance(mock_games, dict) assert not mock_games
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="home", domain=DOMAIN, data={CONF_HOST: "192.168.1.123"}, unique_id="unique_thingy", )
Mock setting up a config entry.
def mock_setup_entry() -> Generator[None, None, None]: """Mock setting up a config entry.""" with patch( "homeassistant.components.pure_energie.async_setup_entry", return_value=True ): yield
Return a mocked Pure Energie client.
def mock_pure_energie_config_flow( request: pytest.FixtureRequest, ) -> Generator[None, MagicMock, None]: """Return a mocked Pure Energie client.""" with patch( "homeassistant.components.pure_energie.config_flow.GridNet", autospec=True ) as pure_energie_mock: pure_energie = pure_energie_mock.return_value pure_energie.device.return_value = GridNetDevice.from_dict( json.loads(load_fixture("device.json", DOMAIN)) ) yield pure_energie
Return a mocked Pure Energie client.
def mock_pure_energie(): """Return a mocked Pure Energie client.""" with patch( "homeassistant.components.pure_energie.GridNet", autospec=True ) as pure_energie_mock: pure_energie = pure_energie_mock.return_value pure_energie.smartbridge = AsyncMock( return_value=SmartBridge.from_dict( json.loads(load_fixture("pure_energie/smartbridge.json")) ) ) pure_energie.device = AsyncMock( return_value=GridNetDevice.from_dict( json.loads(load_fixture("pure_energie/device.json")) ) ) yield pure_energie_mock
Define a fixture to return a mocked aiopurple API object.
def api_fixture(get_sensors_response): """Define a fixture to return a mocked aiopurple API object.""" return Mock( async_check_api_key=AsyncMock(), get_map_url=Mock(return_value="http://example.com"), sensors=Mock( async_get_nearby_sensors=AsyncMock( return_value=[ NearbySensorResult(sensor=sensor, distance=1.0) for sensor in get_sensors_response.data.values() ] ), async_get_sensors=AsyncMock(return_value=get_sensors_response), ), )
Define a config entry fixture.
def config_entry_fixture(hass, config_entry_data, config_entry_options): """Define a config entry fixture.""" entry = MockConfigEntry( domain=DOMAIN, title="abcde", unique_id=TEST_API_KEY, data=config_entry_data, options=config_entry_options, ) entry.add_to_hass(hass) return entry
Define a config entry data fixture.
def config_entry_data_fixture(): """Define a config entry data fixture.""" return { "api_key": TEST_API_KEY, }
Define a config entry options fixture.
def config_entry_options_fixture(): """Define a config entry options fixture.""" return { "sensor_indices": [TEST_SENSOR_INDEX1], }
Define a fixture to mock an aiopurpleair GetSensorsResponse object.
def get_sensors_response_fixture(): """Define a fixture to mock an aiopurpleair GetSensorsResponse object.""" return GetSensorsResponse.parse_raw( load_fixture("get_sensors_response.json", "purpleair") )
Fixture to provide a aioclient mocker.
def requests_mock_fixture(requests_mock: Mocker) -> None: """Fixture to provide a aioclient mocker.""" requests_mock.get( PushBullet.DEVICES_URL, text=load_fixture("devices.json", "pushbullet"), ) requests_mock.get( PushBullet.ME_URL, text=load_fixture("user_info.json", "pushbullet"), ) requests_mock.get( PushBullet.CHATS_URL, text=load_fixture("chats.json", "pushbullet"), ) requests_mock.get( PushBullet.CHANNELS_URL, text=load_fixture("channels.json", "pushbullet"), )
Patch pushbullet setup entry.
def pushbullet_setup_fixture(): """Patch pushbullet setup entry.""" with patch( "homeassistant.components.pushbullet.async_setup_entry", return_value=True ): yield
Mock pushover.
def mock_pushover(): """Mock pushover.""" with patch( "pushover_complete.PushoverAPI._generic_post", return_value={} ) as mock_generic_post: yield mock_generic_post
Patch pushover setup entry.
def pushover_setup_fixture(): """Patch pushover setup entry.""" with patch( "homeassistant.components.pushover.async_setup_entry", return_value=True ): yield
Mock pushover.
def mock_pushover(): """Mock pushover.""" with patch( "pushover_complete.PushoverAPI._generic_post", return_value={} ) as mock_generic_post: yield mock_generic_post
Return the default mocked config entry.
def mock_config_entry() -> MockConfigEntry: """Return the default mocked config entry.""" return MockConfigEntry( title="12345", domain=DOMAIN, data={CONF_API_KEY: "tskey-MOCK", CONF_SYSTEM_ID: 12345}, 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.pvoutput.async_setup_entry", return_value=True ) as mock_setup: yield mock_setup
Return a mocked PVOutput client.
def mock_pvoutput() -> Generator[None, MagicMock, None]: """Return a mocked PVOutput client.""" with ( patch( "homeassistant.components.pvoutput.coordinator.PVOutput", autospec=True ) as pvoutput_mock, patch( "homeassistant.components.pvoutput.config_flow.PVOutput", new=pvoutput_mock ), ): pvoutput = pvoutput_mock.return_value pvoutput.status.return_value = Status.from_dict( load_json_object_fixture("status.json", DOMAIN) ) pvoutput.system.return_value = System.from_dict( load_json_object_fixture("system.json", DOMAIN) ) yield pvoutput
Ensure that sensor has a valid state and attributes.
def check_valid_state(state, tariff: str, value=None, key_attr=None): """Ensure that sensor has a valid state and attributes.""" assert state assert ( state.attributes[ATTR_UNIT_OF_MEASUREMENT] == f"{CURRENCY_EURO}/{UnitOfEnergy.KILO_WATT_HOUR}" ) try: _ = float(state.state) # safety margins for current electricity price (it shouldn't be out of [0, 0.5]) assert -0.1 < float(state.state) < 0.5 assert state.attributes[ATTR_TARIFF] == tariff except ValueError: pass if value is not None and isinstance(value, str): assert state.state == value elif value is not None: assert abs(float(state.state) - value) < 1e-6 if key_attr is not None: assert abs(float(state.state) - state.attributes[key_attr]) < 1e-6