Home Information - Your home, your data, organized.
Python
Add generalized external API timeout protection framework (#188)
cassandra-ai-agent5d61c49ee175
diff --git a/src/hi/apps/common/external_api_mixin.py b/src/hi/apps/common/external_api_mixin.pynew file mode 100644index 00000000..485e30b5--- /dev/null+++ b/src/hi/apps/common/external_api_mixin.py@@ -0,0 +1,103 @@+import asyncio+import logging+from asgiref.sync import sync_to_async+++class ExternalApiMixin:+ """+ Mixin providing timeout protection for external API calls.+ Can be used by any class that needs to make external API calls with timeout protection.+ """++ def get_api_timeout(self) -> float:+ """+ Get timeout for external API calls in seconds.+ Classes can override to provide custom timeouts.+ """+ return 30.0++ def _get_logger(self):+ """Get logger for this class. Override if logger is stored differently."""+ if hasattr(self, '_logger'):+ return self._logger+ elif hasattr(self, 'logger'):+ return self.logger+ else:+ return logging.getLogger(self.__class__.__module__)++ async def safe_external_api_call(self, api_func, *args, **kwargs):+ """+ Wrapper for external API calls with timeout protection and error handling.++ Args:+ api_func: The API function to call (sync or async)+ *args: Arguments to pass to the API function+ **kwargs: Keyword arguments to pass to the API function++ Returns:+ The result of the API call++ Raises:+ asyncio.TimeoutError: If the API call times out+ Exception: Any other exception from the API call+ """+ timeout = self.get_api_timeout()+ logger = self._get_logger()++ try:+ # Determine if the function is async or sync+ if asyncio.iscoroutinefunction(api_func):+ # Async function - call directly with timeout+ return await asyncio.wait_for(+ api_func(*args, **kwargs),+ timeout=timeout+ )+ else:+ # Sync function - wrap with sync_to_async and timeout+ return await asyncio.wait_for(+ sync_to_async(api_func, thread_sensitive=True)(*args, **kwargs),+ timeout=timeout+ )+ except asyncio.TimeoutError:+ logger.error(f'External API call timed out after {timeout} seconds in {self.__class__.__name__}')+ raise+ except Exception as e:+ logger.error(f'External API call failed in {self.__class__.__name__}: {e}')+ raise++ def safe_external_api_call_sync(self, api_func, *args, timeout=None, **kwargs):+ """+ Synchronous wrapper for external API calls with timeout protection.+ Useful for sync contexts like requests.get() calls.++ Args:+ api_func: The API function to call (must be sync)+ *args: Arguments to pass to the API function+ timeout: Optional timeout override+ **kwargs: Keyword arguments to pass to the API function++ Returns:+ The result of the API call++ Raises:+ requests.exceptions.Timeout: If the API call times out+ Exception: Any other exception from the API call+ """+ if timeout is None:+ timeout = self.get_api_timeout()++ logger = self._get_logger()++ try:+ # For requests library calls, pass timeout parameter+ if hasattr(api_func, '__module__') and 'requests' in str(api_func.__module__):+ return api_func(*args, timeout=timeout, **kwargs)+ else:+ # For other sync functions, we can't easily add timeout here+ # This would need to be handled at a higher level with threading+ func_name = getattr(api_func, '__name__', str(type(api_func).__name__))+ logger.warning(f'sync timeout not implemented for {func_name}, falling back to no timeout')+ return api_func(*args, **kwargs)+ except Exception as e:+ logger.error(f'External API call failed in {self.__class__.__name__}: {e}')+ raisediff --git a/src/hi/apps/common/tests/test_external_api_mixin.py b/src/hi/apps/common/tests/test_external_api_mixin.pynew file mode 100644index 00000000..f647ec43--- /dev/null+++ b/src/hi/apps/common/tests/test_external_api_mixin.py@@ -0,0 +1,234 @@+import asyncio+import logging+import time+from unittest.mock import Mock, patch+from unittest import IsolatedAsyncioTestCase++from hi.apps.common.external_api_mixin import ExternalApiMixin+++class TestExternalApiMixin(IsolatedAsyncioTestCase):+ """Test the ExternalApiMixin timeout protection functionality."""++ def setUp(self):+ # Create a test class that uses the mixin+ class TestClass(ExternalApiMixin):+ def __init__(self):+ self._logger = logging.getLogger(__name__)++ def get_api_timeout(self):+ return 0.1 # Very short timeout for fast tests++ self.test_instance = TestClass()++ async def test_safe_external_api_call_with_sync_function_success(self):+ """Test successful sync function call with timeout protection."""+ def mock_api_call():+ return "success"++ result = await self.test_instance.safe_external_api_call(mock_api_call)+ self.assertEqual(result, "success")++ async def test_safe_external_api_call_with_async_function_success(self):+ """Test successful async function call with timeout protection."""+ async def mock_async_api_call():+ return "async_success"++ result = await self.test_instance.safe_external_api_call(mock_async_api_call)+ self.assertEqual(result, "async_success")++ async def test_safe_external_api_call_sync_timeout(self):+ """Test that sync functions timeout correctly."""+ def slow_api_call():+ time.sleep(0.2) # Longer than our 0.1s timeout+ return "should_not_reach"++ with self.assertRaises(asyncio.TimeoutError):+ await self.test_instance.safe_external_api_call(slow_api_call)++ async def test_safe_external_api_call_async_timeout(self):+ """Test that async functions timeout correctly."""+ async def slow_async_api_call():+ await asyncio.sleep(0.2) # Longer than our 0.1s timeout+ return "should_not_reach"++ with self.assertRaises(asyncio.TimeoutError):+ await self.test_instance.safe_external_api_call(slow_async_api_call)++ async def test_safe_external_api_call_with_arguments(self):+ """Test that arguments are properly passed through."""+ def api_call_with_args(arg1, arg2, kwarg1=None):+ # Make sure this call is fast to avoid timeout+ return f"{arg1}-{arg2}-{kwarg1}"++ # Use a longer timeout class for this test+ class LongerTimeoutClass(ExternalApiMixin):+ def __init__(self):+ self._logger = logging.getLogger(__name__)++ def get_api_timeout(self):+ return 5.0 # Much longer timeout++ test_instance = LongerTimeoutClass()+ result = await test_instance.safe_external_api_call(+ api_call_with_args, "test", "value", kwarg1="extra"+ )+ self.assertEqual(result, "test-value-extra")++ async def test_safe_external_api_call_exception_propagation(self):+ """Test that exceptions from API calls are properly propagated."""+ def failing_api_call():+ raise ValueError("API error")++ with self.assertRaises(ValueError) as cm:+ await self.test_instance.safe_external_api_call(failing_api_call)++ self.assertEqual(str(cm.exception), "API error")++ def test_safe_external_api_call_sync_requests_detection(self):+ """Test that sync wrapper correctly identifies requests library functions."""+ # Create a mock function that looks like requests.get+ mock_requests_func = Mock()+ mock_requests_func.__module__ = 'requests.api'+ mock_requests_func.return_value = Mock()++ self.test_instance.safe_external_api_call_sync(+ mock_requests_func, "http://test.com"+ )++ # Verify timeout was passed+ mock_requests_func.assert_called_once_with("http://test.com", timeout=0.1)++ def test_safe_external_api_call_sync_with_custom_timeout(self):+ """Test sync wrapper with custom timeout override."""+ mock_requests_func = Mock()+ mock_requests_func.__module__ = 'requests.api'+ mock_requests_func.return_value = Mock()++ self.test_instance.safe_external_api_call_sync(+ mock_requests_func, "http://test.com", timeout=5.0+ )++ # Verify custom timeout was used+ mock_requests_func.assert_called_once_with("http://test.com", timeout=5.0)++ def test_safe_external_api_call_sync_non_requests_function(self):+ """Test sync wrapper with non-requests function falls back gracefully."""+ def non_requests_function():+ return "fallback_result"++ with patch.object(self.test_instance._logger, 'warning') as mock_warning:+ result = self.test_instance.safe_external_api_call_sync(non_requests_function)++ self.assertEqual(result, "fallback_result")+ mock_warning.assert_called_once()+ self.assertIn("sync timeout not implemented", mock_warning.call_args[0][0])++ def test_get_api_timeout_default(self):+ """Test default timeout value."""+ # Create instance without timeout override+ class DefaultTimeoutClass(ExternalApiMixin):+ def __init__(self):+ self._logger = logging.getLogger(__name__)++ instance = DefaultTimeoutClass()+ self.assertEqual(instance.get_api_timeout(), 30.0)++ def test_get_logger_with_different_logger_attributes(self):+ """Test that _get_logger finds logger in different attribute names."""+ # Test with _logger attribute+ class WithPrivateLogger(ExternalApiMixin):+ def __init__(self):+ self._logger = logging.getLogger("private")++ instance1 = WithPrivateLogger()+ self.assertEqual(instance1._get_logger().name, "private")++ # Test with logger attribute+ class WithPublicLogger(ExternalApiMixin):+ def __init__(self):+ self.logger = logging.getLogger("public")++ instance2 = WithPublicLogger()+ self.assertEqual(instance2._get_logger().name, "public")++ # Test fallback to module logger+ class WithoutLogger(ExternalApiMixin):+ pass++ instance3 = WithoutLogger()+ expected_logger_name = WithoutLogger.__module__+ self.assertEqual(instance3._get_logger().name, expected_logger_name)+++class TestExternalApiMixinIntegration(IsolatedAsyncioTestCase):+ """Integration tests with real timeout scenarios."""++ def setUp(self):+ class IntegrationTestClass(ExternalApiMixin):+ def __init__(self):+ self._logger = logging.getLogger(__name__)++ def get_api_timeout(self):+ return 0.5 # Half second timeout++ self.test_instance = IntegrationTestClass()++ async def test_monitor_continues_after_timeout_basic(self):+ """Test basic timeout and recovery functionality."""+ # Test that we can make a successful call+ def fast_api():+ return "success"++ result1 = await self.test_instance.safe_external_api_call(fast_api)+ self.assertEqual(result1, "success")++ # Test that we can catch a timeout+ def slow_api():+ time.sleep(1.0) # Longer than 0.5s timeout+ return "should_not_reach"++ with self.assertRaises(asyncio.TimeoutError):+ await self.test_instance.safe_external_api_call(slow_api)++ # The above proves that the timeout mechanism works+ # In practice, monitors continue working after timeouts++ async def test_multiple_concurrent_api_calls_with_timeout(self):+ """Test multiple concurrent API calls with some timing out."""+ async def quick_call():+ await asyncio.sleep(0.1)+ return "quick"++ async def slow_call():+ await asyncio.sleep(1.0) # Will timeout+ return "slow"++ # Run concurrent calls+ results = await asyncio.gather(+ self.test_instance.safe_external_api_call(quick_call),+ self.test_instance.safe_external_api_call(quick_call),+ self.test_instance.safe_external_api_call(slow_call),+ return_exceptions=True+ )++ # First two should succeed, third should timeout+ self.assertEqual(results[0], "quick")+ self.assertEqual(results[1], "quick")+ self.assertIsInstance(results[2], asyncio.TimeoutError)++ async def test_timeout_error_logging(self):+ """Test that timeout errors are properly logged."""+ # Patch the instance's logger directly+ with patch.object(self.test_instance, '_logger') as mock_logger:+ def slow_call():+ time.sleep(1.0)++ with self.assertRaises(asyncio.TimeoutError):+ await self.test_instance.safe_external_api_call(slow_call)++ # Verify error was logged+ mock_logger.error.assert_called_once()+ log_message = mock_logger.error.call_args[0][0]+ self.assertIn("timed out after 0.5 seconds", log_message)+ self.assertIn("IntegrationTestClass", log_message)diff --git a/src/hi/apps/monitor/periodic_monitor.py b/src/hi/apps/monitor/periodic_monitor.pyindex afa5d319..74615272 100644--- a/src/hi/apps/monitor/periodic_monitor.py+++ b/src/hi/apps/monitor/periodic_monitor.py@@ -1,8 +1,10 @@import asyncioimport logging+from hi.apps.common.external_api_mixin import ExternalApiMixin-class PeriodicMonitor:++class PeriodicMonitor(ExternalApiMixin):"""Base class for any content/information that should be automatically,and periodically updated from some external source.diff --git a/src/hi/apps/weather/weather_data_source.py b/src/hi/apps/weather/weather_data_source.pyindex 51fd7227..cbc27273 100644--- a/src/hi/apps/weather/weather_data_source.py+++ b/src/hi/apps/weather/weather_data_source.py@@ -5,6 +5,7 @@ import redisfrom django.conf import settingsimport hi.apps.common.datetimeproxy as datetimeproxy+from hi.apps.common.external_api_mixin import ExternalApiMixinfrom hi.apps.common.redis_client import get_redis_clientfrom hi.apps.console.console_helper import ConsoleSettingsHelperfrom hi.apps.weather.transient_models import DataPointSource@@ -12,7 +13,7 @@ from hi.apps.weather.transient_models import DataPointSourcelogger = logging.getLogger(__name__)-class WeatherDataSource:+class WeatherDataSource(ExternalApiMixin):TRACE = FalseFORCE_CAN_POLL = False # For debugging@@ -46,6 +47,7 @@ class WeatherDataSource:abbreviation = self._abbreviation,priority = self._priority,)+ self._logger = logging.getLogger(self.__class__.__module__)polling_intervals_per_day_limit = requests_per_day_limit / requests_per_polling_intervallimit_polling_interval_secs = ( 24 * 60 * 60 ) / polling_intervals_per_day_limitdiff --git a/src/hi/apps/weather/weather_sources/nws.py b/src/hi/apps/weather/weather_sources/nws.pyindex a9f9fd51..86afd033 100644--- a/src/hi/apps/weather/weather_sources/nws.py+++ b/src/hi/apps/weather/weather_sources/nws.py@@ -498,7 +498,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):return observations_datadef _get_observations_data_from_api( self, station : Station ) -> Dict[ str, Any ]:- observations_response = requests.get( station.observations_url, headers = self._headers )+ observations_response = self.safe_external_api_call_sync( requests.get, station.observations_url, headers = self._headers )observations_response.raise_for_status()observations_data = observations_response.json()return observations_data@@ -524,7 +524,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):return forecast_hourly_datadef _get_forecast_hourly_data_from_api( self, station : Station ) -> Dict[ str, Any ]:- forecast_hourly_response = requests.get( station.forecast_url, headers = self._headers )+ forecast_hourly_response = self.safe_external_api_call_sync( requests.get, station.forecast_url, headers = self._headers )forecast_hourly_response.raise_for_status()forecast_hourly_data = forecast_hourly_response.json()return forecast_hourly_data@@ -550,7 +550,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):return forecast_12h_datadef _get_forecast_12h_data_from_api( self, station : Station ) -> Dict[ str, Any ]:- forecast_12h_response = requests.get( station.forecast_url, headers = self._headers )+ forecast_12h_response = self.safe_external_api_call_sync( requests.get, station.forecast_url, headers = self._headers )forecast_12h_response.raise_for_status()forecast_12h_data = forecast_12h_response.json()return forecast_12h_data@@ -586,7 +586,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):# Can cache this data, expires 12 hours-ish (they do not change often)points_data = self._get_points_data( geographic_location = geographic_location )stations_url = points_data['properties']['observationStations']- stations_response = requests.get( stations_url, headers = self._headers )+ stations_response = self.safe_external_api_call_sync( requests.get, stations_url, headers = self._headers )stations_response.raise_for_status()stations_data = stations_response.json()return stations_data@@ -613,7 +613,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):def _get_points_data_from_api( self, geographic_location : GeographicLocation ) -> Dict[ str, Any ]:# Can cache this data, expires 12 hours-ish (they do not change often)points_url = f'{self.BASE_URL}points/{geographic_location.latitude},{geographic_location.longitude}'- points_response = requests.get( points_url, headers = self._headers )+ points_response = self.safe_external_api_call_sync( requests.get, points_url, headers = self._headers )points_response.raise_for_status()points_data = points_response.json()return points_data@@ -1031,7 +1031,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):alerts_url = f'{self.BASE_URL}alerts/active?point={geographic_location.latitude},{geographic_location.longitude}'logger.debug(f'NWS alerts API request: {alerts_url}')- response = requests.get(alerts_url, headers=self._headers)+ response = self.safe_external_api_call_sync( requests.get, alerts_url, headers=self._headers )response.raise_for_status()alerts_data = response.json()return alerts_datadiff --git a/src/hi/apps/weather/weather_sources/openmeteo.py b/src/hi/apps/weather/weather_sources/openmeteo.pyindex 0a75be18..bc1a121e 100644--- a/src/hi/apps/weather/weather_sources/openmeteo.py+++ b/src/hi/apps/weather/weather_sources/openmeteo.py@@ -735,7 +735,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"hourly=temperature_2m,relativehumidity_2m,dewpoint_2m,precipitation,pressure_msl&"f"units=metric")- response = requests.get(url, headers = self._headers)+ response = self.safe_external_api_call_sync( requests.get, url, headers = self._headers )response.raise_for_status()current_data = response.json()return current_data@@ -769,7 +769,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"forecast_days=7&"f"units=metric")- response = requests.get(url, headers = self._headers)+ response = self.safe_external_api_call_sync( requests.get, url, headers = self._headers )response.raise_for_status()forecast_data = response.json()return forecast_data@@ -803,7 +803,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"forecast_days=14&"f"units=metric")- response = requests.get(url, headers = self._headers)+ response = self.safe_external_api_call_sync( requests.get, url, headers = self._headers )response.raise_for_status()forecast_data = response.json()return forecast_data@@ -848,7 +848,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):f"daily=weathercode,temperature_2m_max,temperature_2m_min,precipitation_sum&"f"units=metric")- response = requests.get(url, headers = self._headers)+ response = self.safe_external_api_call_sync( requests.get, url, headers = self._headers )response.raise_for_status()historical_data = response.json()return historical_datadiff --git a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.pyindex 160072e7..50f9134f 100644--- a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py+++ b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py@@ -269,7 +269,7 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):f"date={target_date.isoformat()}&"f"formatted=0") # Get ISO format times- response = requests.get(url, headers = self._headers)+ response = self.safe_external_api_call_sync( requests.get, url, headers = self._headers )response.raise_for_status()api_data = response.json()return api_datadiff --git a/src/hi/apps/weather/weather_sources/usno.py b/src/hi/apps/weather/weather_sources/usno.pyindex 7c553a1c..adce5cfb 100644--- a/src/hi/apps/weather/weather_sources/usno.py+++ b/src/hi/apps/weather/weather_sources/usno.py@@ -385,7 +385,7 @@ class USNO(WeatherDataSource, WeatherMixin):logger.debug(f'USNO API request: {url}')- response = requests.get(url, headers = self._headers)+ response = self.safe_external_api_call_sync( requests.get, url, headers = self._headers )response.raise_for_status()api_data = response.json()return api_datadiff --git a/src/hi/services/hass/monitors.py b/src/hi/services/hass/monitors.pyindex 7986a8e8..514ef41b 100644--- a/src/hi/services/hass/monitors.py+++ b/src/hi/services/hass/monitors.py@@ -49,7 +49,7 @@ class HassMonitor( PeriodicMonitor, HassMixin, SensorResponseMixin ):if not hass_manager:return- id_to_hass_state_map = hass_manager.fetch_hass_states_from_api( verbose = False )+ id_to_hass_state_map = await self.safe_external_api_call( hass_manager.fetch_hass_states_from_api, verbose = False )logger.debug( f'Fetched {len(id_to_hass_state_map)} HAss States' )current_datetime = datetimeproxy.now()diff --git a/src/hi/services/zoneminder/monitors.py b/src/hi/services/zoneminder/monitors.pyindex 9b7ddbe5..bc638556 100644--- a/src/hi/services/zoneminder/monitors.py+++ b/src/hi/services/zoneminder/monitors.py@@ -1,4 +1,3 @@-from asgiref.sync import sync_to_asyncfrom cachetools import TTLCachefrom datetime import datetimeimport logging@@ -45,8 +44,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )if not zm_manager:return_ = await self.sensor_response_manager_async() # Allows async use of self.sensor_response_manager()- self._zm_tzname = await sync_to_async( zm_manager.get_zm_tzname,- thread_sensitive = True )()+ self._zm_tzname = await self.safe_external_api_call( zm_manager.get_zm_tzname )self._poll_from_datetime = datetimeproxy.now()zm_manager.register_change_listener( self.refresh )self._was_initialized = True@@ -94,7 +92,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )'from': tz_adjusted_poll_from_datetime.isoformat(), # "from" only looks at event start time'tz': self._zm_tzname,}- zm_events = await sync_to_async( self.zm_manager().get_zm_events )( options = options )+ zm_events = await self.safe_external_api_call( self.zm_manager().get_zm_events, options = options )logger.debug( f'Found {len(zm_events)} new ZM events' )# Sensor readings and state value transitions are points in time,@@ -138,7 +136,7 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )# If there are no events for monitors/states, we still want to emit the# sensor response of it being idle.#- zm_monitors = await sync_to_async( self.zm_manager().get_zm_monitors )()+ zm_monitors = await self.safe_external_api_call( self.zm_manager().get_zm_monitors )for zm_monitor in zm_monitors:if zm_monitor.id() not in zm_monitor_ids_seen:idle_sensor_response = self._create_idle_sensor_response(@@ -263,9 +261,8 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )current_poll_datetime = datetimeproxy.now()sensor_response_map = dict()- zm_monitors = await sync_to_async( self.zm_manager().get_zm_monitors )(- force_load = self.CACHING_DISABLED,- )+ zm_monitors = await self.safe_external_api_call( self.zm_manager().get_zm_monitors,+ force_load = self.CACHING_DISABLED )for zm_monitor in zm_monitors:function_sensor_response = self._create_monitor_function_sensor_response(zm_monitor = zm_monitor,@@ -281,9 +278,8 @@ class ZoneMinderMonitor( PeriodicMonitor, ZoneMinderMixin, SensorResponseMixin )sensor_response_map = dict()active_run_state_name = None- zm_states = await sync_to_async( self.zm_manager().get_zm_states )(- force_load = self.CACHING_DISABLED,- )+ zm_states = await self.safe_external_api_call( self.zm_manager().get_zm_states,+ force_load = self.CACHING_DISABLED )for zm_state in zm_states:if zm_state.active():active_run_state_name = zm_state.name()diff --git a/src/hi/testing/base_test_case.py b/src/hi/testing/base_test_case.pyindex 60798fc9..42d85970 100644--- a/src/hi/testing/base_test_case.py+++ b/src/hi/testing/base_test_case.py@@ -3,6 +3,7 @@ import loggingimport tempfilefrom contextlib import contextmanagerfrom typing import Dict+from unittest.mock import Mockfrom django.contrib.auth.models import AnonymousUserfrom django.contrib.auth.models import User as UserType@@ -251,6 +252,32 @@ class BaseTestCase(TestCase):self.assertEqual( actual_content, expected_content,f"File content should match for: {full_path}")+ def create_mock_requests_get(self, return_data=None, status_code=200, raise_for_status_error=None):+ """+ Create a properly configured mock for requests.get() that works with timeout protection.++ Args:+ return_data: Data to return from response.json()+ status_code: HTTP status code (default: 200)+ raise_for_status_error: Exception to raise from raise_for_status() if any++ Returns:+ Mock object configured to behave like requests.get+ """+ mock_response = Mock()+ mock_response.json.return_value = return_data or {}+ mock_response.status_code = status_code++ if raise_for_status_error:+ mock_response.raise_for_status.side_effect = raise_for_status_error+ else:+ mock_response.raise_for_status.return_value = None++ mock_get = Mock(return_value=mock_response)+ mock_get.__name__ = 'get' # Required for external_api_mixin timeout logging++ return mock_get+@dataclassclass MockSession(dict):