diff --git a/homeassistant/components/onvif/camera.py b/homeassistant/components/onvif/camera.py index 235a78e3db61..baae34aacd3f 100644 --- a/homeassistant/components/onvif/camera.py +++ b/homeassistant/components/onvif/camera.py @@ -143,19 +143,21 @@ class ONVIFCameraEntity(ONVIFBaseEntity, Camera): if self._stream_uri_future: return await self._stream_uri_future loop = asyncio.get_running_loop() - self._stream_uri_future = loop.create_future() + self._stream_uri_future = future = loop.create_future() try: uri_no_auth = await self.device.async_get_stream_uri(self.profile) except (TimeoutError, Exception) as err: LOGGER.error("Failed to get stream uri: %s", err) - if self._stream_uri_future: - self._stream_uri_future.set_exception(err) + self._stream_uri_future = None + future.set_exception(err) + # Nothing may be awaiting the future, mark the exception as retrieved + future.exception() raise url = URL(uri_no_auth) url = url.with_user(self.device.username) url = url.with_password(self.device.password) self._stream_uri = str(url) - self._stream_uri_future.set_result(self._stream_uri) + future.set_result(self._stream_uri) return self._stream_uri async def async_perform_ptz( diff --git a/tests/components/onvif/test_camera.py b/tests/components/onvif/test_camera.py new file mode 100644 index 000000000000..bb30cb66dd3d --- /dev/null +++ b/tests/components/onvif/test_camera.py @@ -0,0 +1,32 @@ +"""Test the ONVIF camera platform.""" + +from unittest.mock import AsyncMock + +import pytest + +from homeassistant.components.camera import async_get_stream_source +from homeassistant.core import HomeAssistant + +from . import PASSWORD, USERNAME, setup_onvif_integration + +ENTITY_ID = "camera.testcamera_profile1" + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_stream_uri_retried_after_failure(hass: HomeAssistant) -> None: + """Test the stream URI is fetched again after a failed attempt.""" + _, _, device = await setup_onvif_integration(hass) + device.username = USERNAME + device.password = PASSWORD + device.async_get_stream_uri = AsyncMock( + side_effect=[TimeoutError, "rtsp://1.2.3.4/stream"] + ) + + with pytest.raises(TimeoutError): + await async_get_stream_source(hass, ENTITY_ID) + + assert ( + await async_get_stream_source(hass, ENTITY_ID) + == f"rtsp://{USERNAME}:{PASSWORD}@1.2.3.4/stream" + ) + assert device.async_get_stream_uri.await_count == 2