async def test_http_connection_errors_is_retried(self): self.add_get_token_imds_response(token='token') self.add_get_role_name_imds_response() # Connection related errors should be retried self.add_imds_connection_error(ClientConnectionError('')) self.add_get_credentials_imds_response() result = await AioInstanceMetadataFetcher( num_attempts=2).retrieve_iam_role_credentials() self.assertEqual(result, self._expected_creds)
async def test_post_index_iac_service_connection_error(self): with aioresponses(passthrough=[str(self.server._root)]) as mocked: mocked.get(self.iac_url, exception=ClientConnectionError('Failed')) with self.assertLogs('respondent-home', 'ERROR') as cm: response = await self.client.request("POST", self.post_index, data=self.form_data) self.assertLogLine(cm, "Client failed to connect to iac service") self.assertEqual(response.status, 500) self.assertIn('Sorry, something went wrong', str(await response.content.read()))
async def test_refresh_expired_stream_failure(hass, aiohttp_client): """Tests a failure when refreshing the stream.""" now = utcnow() stream_1_expiration = now + datetime.timedelta(seconds=90) stream_2_expiration = now + datetime.timedelta(seconds=180) responses = [ FakeResponse({ "results": { "streamUrls": { "rtspUrl": "rtsp://some/url?auth=g.1.streamingToken" }, "streamExtensionToken": "g.1.extensionToken", "streamToken": "g.1.streamingToken", "expiresAt": stream_1_expiration.isoformat(timespec="seconds"), }, }), # Extending the stream fails with arbitrary error FakeResponse(error=ClientConnectionError()), # Next attempt to get a stream fetches a new url FakeResponse({ "results": { "streamUrls": { "rtspUrl": "rtsp://some/url?auth=g.2.streamingToken" }, "streamExtensionToken": "g.2.extensionToken", "streamToken": "g.2.streamingToken", "expiresAt": stream_2_expiration.isoformat(timespec="seconds"), }, }), ] await async_setup_camera( hass, DEVICE_TRAITS, auth=FakeAuth(responses), ) assert len(hass.states.async_all()) == 1 cam = hass.states.get("camera.my_camera") assert cam is not None assert cam.state == STATE_IDLE stream_source = await camera.async_get_stream_source( hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.1.streamingToken" # Fire alarm when stream is nearing expiration, causing it to be extended. # The stream expires. next_update = now + datetime.timedelta(seconds=65) await fire_alarm(hass, next_update) # The stream is entirely refreshed stream_source = await camera.async_get_stream_source( hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.2.streamingToken"
async def _request(url, method, proxy, timeout, verify_ssl): async with SEMAPHORE: async with ClientSession(connector=TCPConnector(verify_ssl=verify_ssl)) as session: async with getattr(session, method.lower())(url, proxy=proxy, timeout=timeout) as resp: if resp.status == 200: content = await resp.read() return content if proxy: raise ClientHttpProxyError(history='%d get' % resp.status, request_info=url) else: raise ClientConnectionError('%d get' % resp.status)
async def test_post_index_with_build_connection_error(self): with aioresponses(passthrough=[str(self.server._root)]) as mocked: mocked.get(self.iac_url, payload=self.iac_json) mocked.get(self.case_url, payload=self.case_json) mocked.get(self.collection_instrument_url, exception=ClientConnectionError('Failed')) with self.assertLogs('respondent-home', 'ERROR') as cm: response = await self.client.request("POST", self.post_index, allow_redirects=False, data=self.form_data) self.assertLogLine(cm, "Service connection error", message='Failed') self.assertEqual(response.status, 500) self.assertIn('Sorry, something went wrong', str(await response.content.read()))
def test_connection_errors(self): with self.assertRaises(JSONBadGateway): with client_exception_handler(): raise ClientConnectionError() with self.assertRaises(JSONBadGateway): with client_exception_handler(): connection_key = ConnectionKey( "http://foo.bar", 80, False ) raise ClientConnectorError( connection_key=connection_key, os_error=OSError(1, "one") ) with self.assertRaises(JSONBadGateway): with client_exception_handler(): raise ClientResponseError( request_info="something", history="something" )
def test_formatter(self): formatter = ErrorFormatter(DefaultErrorFormatter()) formatter.register(ClientError, ClientErrorFormatter()) try: raise ConnectionError() from ClientConnectionError() except Exception as e: self.assertIn("aiohttp.client_exceptions.ClientConnectionError", ClientErrorFormatter().format(e)) try: raise ConnectionError() from TimeoutError() except Exception as e: self.assertIn("超时", ClientErrorFormatter().format(e)) try: raise HandlerError() from ValueError("输入错误") except Exception as e: self.assertIn("输入错误", DefaultErrorFormatter().format(e)) try: raise ValueError("输入错误") except Exception as e: self.assertIn("输入错误", DefaultErrorFormatter().format(e))
async def set_brightness(self, brightness: int) -> None: """Set the mocked brightness.""" if self.is_offline: raise ClientConnectionError() self.brightness = brightness
async def get_brightness(self) -> int: """Get the mocked brightness.""" if self.is_offline: raise ClientConnectionError() return self.brightness
async def set_is_on(self, is_on: bool) -> None: """Set the mocked on/off state.""" if self.is_offline: raise ClientConnectionError() self.is_on = is_on
async def get_is_on(self) -> bool: """Get the mocked on/off state.""" if self.is_offline: raise ClientConnectionError() return self.is_on
async def get_device_info(self): """Get the mocked device info.""" if self.is_offline: raise ClientConnectionError() return self.device_info
async def post(self, *args, **kwargs): raise ClientConnectionError()
async def set_brightness(self, brightness: int) -> None: """Set the mocked brightness.""" if self.is_offline: raise ClientConnectionError() self.brightness = {"mode": "enabled", "value": brightness}
async def turn_off(self) -> None: """Set the mocked off state.""" if self.is_offline: raise ClientConnectionError() self.state = False