async def test_connection_error_then_valid_url( self, mock_aioresponse: aioresponses, capsys: CaptureFixture) -> None: """ The program can continue making requests in the event of a connection error exception. """ invalid_url = "barcom" valid_url = "foo.com" urls = [invalid_url, valid_url] status = 200 connection_key = ConnectionKey( host=invalid_url, port=80, is_ssl=False, ssl=None, proxy=None, proxy_auth=None, proxy_headers_hash=None, ) os_error = gaierror(8, "nodename nor servname provided, or not known") exception = ClientConnectorError(connection_key=connection_key, os_error=os_error) mock_aioresponse.get(invalid_url, exception=exception) mock_aioresponse.get(valid_url, status=status) await make_requests_and_print_results(url_list=urls, timeout=1) expected_output_invalid = "Connection error resolving barcom\n" expected_output_valid = "Request to foo.com responded with 200" captured = capsys.readouterr() assert expected_output_invalid in captured.out assert expected_output_valid in captured.out
async def test_should_retry(): strategies = [TestAuthenticationStrategy(), TestRefreshSessionStrategy(), TestReadDatafeedStrategy()] connection_key = Mock() connection_key.ssl = "ssl" exception_from_a_timeout = ClientConnectorError(connection_key, TimeoutError()) exception_from_a_timeout.__cause__ = TimeoutError() thing = FixedChainedExceptions([ApiException(429), ApiException(500), exception_from_a_timeout]) for s in strategies: s._retry_config = minimal_retry_config_with_attempts(4) value = await s._retryable_coroutine(thing) assert value is True assert thing.call_count == 4 thing.reset() # Reset the counters
async def test_request_repeated_on_connection_errors(self): """Requests are repeated in the case of connection errors.""" self.bot.http_session.post = MagicMock( side_effect=ClientConnectorError(Mock(), Mock())) result = await send_to_paste_service("") self.assertEqual(self.bot.http_session.post.call_count, FAILED_REQUEST_ATTEMPTS) self.assertIsNone(result)
async def test_client_connector_error(mocker, mock_aioresponse, download_order): """Tests ClientConnectorError.""" mock = mocker.Mock() mock_aioresponse.get(InstanceResource.URL_TWITTER_IMAGE, status=200, exception=ClientConnectorError(mock, OSError())) with pytest.raises(ClientConnectorError) as error: semaphore = asyncio.Semaphore(5) async with aiohttp.ClientSession() as client_session: await MediaDownloadCoroutine(MediaSaveCoroutine() ).execute(semaphore, client_session, download_order) assert "Cannot connect to host" in str(error.value)
async def test_form_cannot_connect(hass): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}) with patch( "homeassistant.components.kmtronic.config_flow.KMTronicHubAPI.async_get_status", side_effect=ClientConnectorError(None, Mock()), ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "******", "password": "******", }, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "cannot_connect"}
async def test_coordinator_client_connector_error(hass: HomeAssistant): """Test ClientConnectorError on coordinator update.""" entry = MockConfigEntry(domain=DOMAIN, data=CONFIG) entry.add_to_hass(hass) with patch( "homeassistant.components.airzone.AirzoneLocalApi.get_hvac", return_value=HVAC_MOCK, ) as mock_hvac: await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() mock_hvac.assert_called_once() mock_hvac.reset_mock() mock_hvac.side_effect = ClientConnectorError(MagicMock(), MagicMock()) async_fire_time_changed(hass, utcnow() + SCAN_INTERVAL) await hass.async_block_till_done() mock_hvac.assert_called_once() state = hass.states.get("sensor.despacho_temperature") assert state.state == STATE_UNAVAILABLE
async def test_connection_error(self, mock_aioresponse: aioresponses, capsys: CaptureFixture) -> None: """ An exception can be raised if a request results in failure. """ url = "foo.com" connection_key = ConnectionKey( host=url, port=80, is_ssl=False, ssl=None, proxy=None, proxy_auth=None, proxy_headers_hash=None, ) os_error = gaierror(8, "nodename nor servname provided, or not known") exception = ClientConnectorError(connection_key=connection_key, os_error=os_error) mock_aioresponse.get(url, exception=exception) await make_requests_and_print_results(url_list=[url], timeout=1) captured = capsys.readouterr() expected_output = "Connection error resolving foo.com\n" assert expected_output in captured.out
def mock_client_connector_error() -> ClientConnectorError: """Return a mocked `aiohttp.ClientConnectorError`.""" return ClientConnectorError(Mock(), Mock())
async def _create_direct_connection( self, req: 'ClientRequest', traces: List['Trace'], timeout: 'ClientTimeout', *, client_error: Type[Exception] = ClientConnectorError ) -> Tuple[asyncio.Transport, ResponseHandler]: sslcontext = self._get_ssl_context(req) fingerprint = self._get_fingerprint(req) try: # Cancelling this lookup should not cancel the underlying lookup # or else the cancel event will get broadcast to all the waiters # across all connections. host = req.url.raw_host assert host is not None port = req.port assert port is not None headers = req.headers sni_host = None for head, value in headers.items(): if head.lower() == 'sni-host': sni_host = headers[head] hosts = await asyncio.shield(self._resolve_host(host, port, sni_host, traces=traces), loop=self._loop) except OSError as exc: # in case of proxy it is not ClientProxyConnectionError # it is problem of resolving proxy ip itself raise ClientConnectorError(req.connection_key, exc) from exc last_exc = None # type: Optional[Exception] for hinfo in hosts: host = hinfo['host'] port = hinfo['port'] try: transp, proto = await self._wrap_create_connection( self._factory, host, port, timeout=timeout, ssl=sslcontext, family=hinfo['family'], proto=hinfo['proto'], flags=hinfo['flags'], server_hostname=hinfo['hostname'] if sslcontext else None, local_addr=self._local_addr, req=req, client_error=client_error) except ClientConnectorError as exc: last_exc = exc continue if req.is_ssl() and fingerprint: try: fingerprint.check(transp) except ServerFingerprintMismatch as exc: transp.close() if not self._cleanup_closed_disabled: self._cleanup_closed_transports.append(transp) last_exc = exc continue return transp, proto else: assert last_exc is not None raise last_exc