async def test_create_async_httpx_client_with_ssl_and_cookies(opp): """Test init async client with ssl and cookies.""" client.get_async_client(opp) httpx_client = client.create_async_httpx_client(opp, cookies={"bla": True}) assert isinstance(httpx_client, httpx.AsyncClient) assert opp.data[client.DATA_ASYNC_CLIENT] != httpx_client
async def test_create_async_httpx_client_without_ssl_and_cookies(opp): """Test init async client without ssl and cookies.""" client.get_async_client(opp, verify_ssl=False) httpx_client = client.create_async_httpx_client(opp, verify_ssl=False, cookies={"bla": True}) assert isinstance(httpx_client, httpx.AsyncClient) assert opp.data[client.DATA_ASYNC_CLIENT_NOVERIFY] != httpx_client
async def test_get_async_client_cleanup(opp): """Test init async client with ssl.""" client.get_async_client(opp) assert isinstance(opp.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient) opp.bus.async_fire(EVENT_OPENPEERPOWER_CLOSE) await opp.async_block_till_done() assert opp.data[client.DATA_ASYNC_CLIENT].is_closed
async def test_get_async_client_cleanup_without_ssl(opp): """Test init async client without ssl.""" client.get_async_client(opp, verify_ssl=False) assert isinstance(opp.data[client.DATA_ASYNC_CLIENT_NOVERIFY], httpx.AsyncClient) opp.bus.async_fire(EVENT_OPENPEERPOWER_CLOSE) await opp.async_block_till_done() assert opp.data[client.DATA_ASYNC_CLIENT_NOVERIFY].is_closed
async def test_warning_close_session_integration(opp, caplog): """Test log warning message when closing the session from integration context.""" with patch( "openpeerpower.helpers.frame.extract_stack", return_value=[ Mock( filename="/home/paulus/openpeerpower/core.py", lineno="23", line="do_something()", ), Mock( filename= "/home/paulus/openpeerpower/components/hue/light.py", lineno="23", line="await session.aclose()", ), Mock( filename="/home/paulus/aiohue/lights.py", lineno="2", line="something()", ), ], ): httpx_session = client.get_async_client(opp) await httpx_session.aclose() assert ( "Detected integration that closes the Open Peer Power httpx client. " "Please report issue for hue using this method at " "openpeerpower/components/hue/light.py, line 23: await session.aclose()" ) in caplog.text
async def async_update(self, log_errors=True): """Get the latest data from REST service with provided method.""" if not self._async_client: self._async_client = get_async_client(self._opp, verify_ssl=self._verify_ssl) _LOGGER.debug("Updating from %s", self._resource) try: response = await self._async_client.request( self._method, self._resource, headers=self._headers, params=self._params, auth=self._auth, data=self._request_data, timeout=self._timeout, ) self.data = response.text self.headers = response.headers except httpx.RequestError as ex: if log_errors: _LOGGER.error("Error fetching data: %s failed with %s", self._resource, ex) self.last_exception = ex self.data = None self.headers = None
async def get_device(opp, host, port, username, password): """Create a Axis device.""" session = get_async_client(opp, verify_ssl=False) device = axis.AxisDevice( Configuration(session, host, port=port, username=username, password=password)) try: with async_timeout.timeout(30): await device.vapix.initialize() return device except axis.Unauthorized as err: LOGGER.warning("Connected to device at %s but not registered", host) raise AuthenticationRequired from err except (asyncio.TimeoutError, axis.RequestError) as err: LOGGER.error("Error connecting to the Axis device at %s", host) raise CannotConnect from err except axis.AxisException as err: LOGGER.exception("Unknown Axis communication error occurred") raise AuthenticationRequired from err
async def async_setup_entry(opp: core.OpenPeerPower, entry: config_entries.ConfigEntry): """Set up the denonavr components from a config entry.""" opp.data.setdefault(DOMAIN, {}) # Connect to receiver connect_denonavr = ConnectDenonAVR( entry.data[CONF_HOST], DEFAULT_TIMEOUT, entry.options.get(CONF_SHOW_ALL_SOURCES, DEFAULT_SHOW_SOURCES), entry.options.get(CONF_ZONE2, DEFAULT_ZONE2), entry.options.get(CONF_ZONE3, DEFAULT_ZONE3), lambda: get_async_client(opp), ) try: await connect_denonavr.async_connect_receiver() except (AvrNetworkError, AvrTimoutError) as ex: raise ConfigEntryNotReady from ex receiver = connect_denonavr.receiver undo_listener = entry.add_update_listener(update_listener) opp.data[DOMAIN][entry.entry_id] = { CONF_RECEIVER: receiver, UNDO_UPDATE_LISTENER: undo_listener, } opp.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def async_camera_image(self): """Return a still image response from the camera.""" try: url = self._still_image_url.async_render(parse_result=False) except TemplateError as err: _LOGGER.error("Error parsing template %s: %s", self._still_image_url, err) return self._last_image if url == self._last_url and self._limit_refetch: return self._last_image try: async_client = get_async_client(self.opp, verify_ssl=self.verify_ssl) response = await async_client.get(url, auth=self._auth, timeout=GET_IMAGE_TIMEOUT) response.raise_for_status() self._last_image = response.content except httpx.TimeoutException: _LOGGER.error("Timeout getting camera image from %s", self._name) return self._last_image except (httpx.RequestError, httpx.HTTPStatusError) as err: _LOGGER.error("Error getting new camera image from %s: %s", self._name, err) return self._last_image self._last_url = url return self._last_image
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool: """Set up Enphase Envoy from a config entry.""" config = entry.data name = config[CONF_NAME] envoy_reader = EnvoyReader( config[CONF_HOST], config[CONF_USERNAME], config[CONF_PASSWORD], inverters=True, async_client=get_async_client(opp), ) async def async_update_data(): """Fetch data from API endpoint.""" data = {} async with async_timeout.timeout(30): try: await envoy_reader.getData() except httpx.HTTPStatusError as err: raise ConfigEntryAuthFailed from err except httpx.HTTPError as err: raise UpdateFailed( f"Error communicating with API: {err}") from err for condition in SENSORS: if condition != "inverters": data[condition] = await getattr(envoy_reader, condition)() else: data[ "inverters_production"] = await envoy_reader.inverters_production( ) _LOGGER.debug("Retrieved data from API: %s", data) return data coordinator = DataUpdateCoordinator( opp, _LOGGER, name=f"envoy {name}", update_method=async_update_data, update_interval=SCAN_INTERVAL, ) try: await coordinator.async_config_entry_first_refresh() except ConfigEntryAuthFailed: envoy_reader.get_inverters = False await coordinator.async_config_entry_first_refresh() opp.data.setdefault(DOMAIN, {})[entry.entry_id] = { COORDINATOR: coordinator, NAME: name, } opp.config_entries.async_setup_platforms(entry, PLATFORMS) return True
async def test_get_async_client_context_manager(opp): """Test using the async client with a context manager does not close the session.""" with patch("httpx.AsyncClient.aclose") as mock_aclose: httpx_session = client.get_async_client(opp) assert isinstance(opp.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient) async with httpx_session: pass assert mock_aclose.call_count == 0
async def test_get_async_client_patched_close(opp): """Test closing the async client does not work.""" with patch("httpx.AsyncClient.aclose") as mock_aclose: httpx_session = client.get_async_client(opp) assert isinstance(opp.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient) with pytest.raises(RuntimeError): await httpx_session.aclose() assert mock_aclose.call_count == 0
def get_api(opp: OpenPeerPower, config_data: dict) -> AbstractGateApi: """Get an api object for config data.""" gate_class = GogoGate2Api if config_data[CONF_DEVICE] == DEVICE_TYPE_ISMARTGATE: gate_class = ISmartGateApi return gate_class( config_data[CONF_IP_ADDRESS], config_data[CONF_USERNAME], config_data[CONF_PASSWORD], httpx_async_client=get_async_client(opp), )
async def async_step_connect(self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Connect to the receiver.""" connect_denonavr = ConnectDenonAVR( self.host, self.timeout, self.show_all_sources, self.zone2, self.zone3, lambda: get_async_client(self.opp), ) try: success = await connect_denonavr.async_connect_receiver() except (AvrNetworkError, AvrTimoutError): success = False if not success: return self.async_abort(reason="cannot_connect") receiver = connect_denonavr.receiver if not self.serial_number: self.serial_number = receiver.serial_number if not self.model_name: self.model_name = (receiver.model_name).replace("*", "") if self.serial_number is not None: unique_id = self.construct_unique_id(self.model_name, self.serial_number) await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() else: _LOGGER.error( "Could not get serial number of host %s, " "unique_id's will not be available", self.host, ) self._async_abort_entries_match({CONF_HOST: self.host}) return self.async_create_entry( title=receiver.name, data={ CONF_HOST: self.host, CONF_TYPE: receiver.receiver_type, CONF_MODEL: self.model_name, CONF_MANUFACTURER: receiver.manufacturer, CONF_SERIAL_NUMBER: self.serial_number, }, )
async def validate_input(opp: OpenPeerPower, data: dict[str, Any]) -> dict[str, Any]: """Validate the user input allows us to connect.""" envoy_reader = EnvoyReader( data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD], inverters=False, async_client=get_async_client(opp), ) try: await envoy_reader.getData() except httpx.HTTPStatusError as err: raise InvalidAuth from err except (RuntimeError, httpx.HTTPError) as err: raise CannotConnect from err
async def test_get_async_client_with_ssl(opp): """Test init async client with ssl.""" client.get_async_client(opp) assert isinstance(opp.data[client.DATA_ASYNC_CLIENT], httpx.AsyncClient)
async def test_get_async_client_without_ssl(opp): """Test init async client without ssl.""" client.get_async_client(opp, verify_ssl=False) assert isinstance(opp.data[client.DATA_ASYNC_CLIENT_NOVERIFY], httpx.AsyncClient)