async def test_verify_url_exception(tmp_path: Path) -> None: class FakeArgs: delete = True dry_run = False json_update = False workers = 2 fa = FakeArgs() fc = FakeConfig() master = Master(fc.get("mirror", "master")) url_fetch_404 = AsyncMock(side_effect=ClientResponseError( code=404, history=(), request_info=None)) master.url_fetch = url_fetch_404 # type: ignore jsonpath = tmp_path / "web" / "json" jsonpath.mkdir(parents=True, exist_ok=True) jsonfile = jsonpath / "bandersnatch" with jsonfile.open("w") as f: f.write( '{"releases":{"1.0":["url":"https://unittests.org/packages/a0/a0/a0a0/package-1.0.0.exe"}]}}' # noqa: E501 ) all_package_files: List[str] = [] await verify(master, fc, "bandersnatch", tmp_path, all_package_files, fa) # type: ignore # noqa: E501 assert jsonfile.exists() assert not all_package_files
async def put(**kwargs) -> dict: """ Method PUT request """ async with aiohttp.ClientSession() as session: LOGGER.debug(kwargs) async with session.put(**kwargs) as response: if response.status == 200: result = await response.json() elif response.status in list(range(400, 499)): result = await response.json() LOGGER.error( f'url: {response}, code: {response.status}, msg: {result}') raise ClientResponseError(request_info=response.request_info, history=response.history, status=response.status, message=response, headers=response.headers, result=result) else: result = None LOGGER.debug("url запроса: %s", response.url) LOGGER.debug("код ответа: %d", response.status) LOGGER.debug("результат ответа от сервера: %s", result) return {'code': response.status, 'result': result}
async def async_http_request(name, session: ClientSession, **kwargs) -> str: """ Invokes aiohttp client session request :param name: :param session: :param kwargs: :return: """ _kwargs = serialize(kwargs) async with session.request(timeout=DEFAULT_REST_REQUEST_TIMEOUT, **_kwargs) as resp: resp_data = await resp.text() description = HTTPCodesDescription.get_description( resp.status, **kwargs) logger.debug("'%s' '%s' %s %s, status: %s, description: %s" "\n\tpayload: %s\n\trequest headers: %s\n\tparams: %s" "\n\tresponse data: %s\n\tresponse headers: %s" % (kwargs['username'], name, kwargs['url'], kwargs['method'].upper(), resp.status, description, kwargs.get('data'), kwargs.get('headers'), kwargs.get('params'), resp_data, dict(resp.headers))) # TODO: replace dirty hack if resp.status not in list(range(200, 209)): raise ClientResponseError(request_info=kwargs, history='', code=resp.status) return resp_data
async def get(**kwargs) -> dict: """ Method GET request """ count = None async with aiohttp.ClientSession() as session: LOGGER.debug("переданные параметры запроса: %s", kwargs) async with session.get(**kwargs) as response: if response.status == 200: result = await response.json() if result.get('results') is not None: count = result.get('count') result = result.get('results') elif response.status in list(range(400, 499)): result = await response.json() LOGGER.error( f'url: {response}, code: {response.status}, msg: {result}') raise ClientResponseError(request_info=response.request_info, history=response.history, status=response.status, message=response, headers=response.headers) else: result = await response.json() LOGGER.debug("url запроса: %s", response.url) LOGGER.debug("код ответа: %d", response.status) LOGGER.debug("результат ответа от сервера: %s", result) return {'code': response.status, 'result': result, 'count': count}
async def test_get_latest_json_404(tmp_path: Path) -> None: class FakeArgs: delete = True dry_run = False json_update = True workers = 2 fa = FakeArgs() fc = FakeConfig() master = Master(fc.get("mirror", "master")) url_fetch_404 = AsyncMock(side_effect=ClientResponseError( code=404, history=(), request_info=None)) master.url_fetch = url_fetch_404 # type: ignore jsonpath = tmp_path / "web" / "json" jsonpath.mkdir(parents=True) jsonfile = jsonpath / "bandersnatch" jsonfile.touch() all_package_files: List[str] = [] await verify(master, fc, "bandersnatch", tmp_path, all_package_files, fa) # type: ignore # noqa: E501 assert not jsonfile.exists() assert not all_package_files
def raise_for_status(self): """Raise error if status is 400 or higher.""" if self.status >= 400: raise ClientResponseError(None, None, code=self.status, headers=self.headers)
def patch_bond_action_returns_clientresponseerror(): """Patch Bond API action endpoint to throw ClientResponseError.""" return patch( "homeassistant.components.bond.Bond.action", side_effect=ClientResponseError( request_info=None, history=None, code=405, message="Method Not Allowed" ), )
def raise_for_status(self): """Raise error if status is 400 or higher.""" if self.status >= 400: request_info = mock.Mock(real_url="http://example.com") raise ClientResponseError( request_info=request_info, history=None, code=self.status, headers=self.headers, )
async def test_unknown_api_error(hass, smartthings_mock): """Test an error is shown when there is an unknown API error.""" flow = SmartThingsFlowHandler() flow.hass = hass smartthings_mock.return_value.apps.return_value = mock_coro( exception=ClientResponseError(None, None, status=500)) result = await flow.async_step_user({'access_token': str(uuid4())}) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['step_id'] == 'user' assert result['errors'] == {'base': 'app_setup_error'}
async def test_token_forbidden(hass, smartthings_mock): """Test an error is shown when the token is forbidden.""" flow = SmartThingsFlowHandler() flow.hass = hass smartthings_mock.return_value.apps.return_value = mock_coro( exception=ClientResponseError(None, None, status=403)) result = await flow.async_step_user({'access_token': str(uuid4())}) assert result['type'] == data_entry_flow.RESULT_TYPE_FORM assert result['step_id'] == 'user' assert result['errors'] == {'access_token': 'token_forbidden'}
async def test_form(hass: HomeAssistant) -> None: """Test that the form is served with valid input.""" with patch( "homeassistant.components.airzone.async_setup_entry", return_value=True, ) as mock_setup_entry, patch( "homeassistant.components.airzone.AirzoneLocalApi.get_hvac", return_value=HVAC_MOCK, ), patch( "homeassistant.components.airzone.AirzoneLocalApi.get_hvac_systems", side_effect=ClientResponseError(MagicMock(), MagicMock()), ), patch( "homeassistant.components.airzone.AirzoneLocalApi.get_webserver", side_effect=ClientResponseError(MagicMock(), MagicMock()), ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == SOURCE_USER assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], CONFIG) await hass.async_block_till_done() conf_entries = hass.config_entries.async_entries(DOMAIN) entry = conf_entries[0] assert entry.state is ConfigEntryState.LOADED assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result[ "title"] == f"Airzone {CONFIG[CONF_HOST]}:{CONFIG[CONF_PORT]}" assert result["data"][CONF_HOST] == CONFIG[CONF_HOST] assert result["data"][CONF_PORT] == CONFIG[CONF_PORT] assert len(mock_setup_entry.mock_calls) == 1
async def test_should_raise_correios_exception_when_client_response_error_returned( self ): with aioresponses() as mock_aioresponse: url = 'https://www2.correios.com.br/sistemas/rastreamento/ctrl/ctrlRastreamento.cfm' mock_aioresponse.post( url, status=503, exception=ClientResponseError('server is unable to handle the request', history=('', '')) ) with pytest.raises(CorreiosException): await CorreiosHttpClient().get_tracking_events('PU524124388BR')
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" )
async def _make_request(self, *args, **kwargs): if self._session is None: self._session = self._session_factory() query_params = kwargs.get('params', {}) query_params = { param: value for param, value in query_params.items() if value is not None } query_params.update(dict(auth_token=self._auth_token)) kwargs.update(dict(params=query_params)) async with self._session.request(*args, **kwargs) as resp: payload = await resp.json() try: resp.raise_for_status() return payload except ClientResponseError as ex: reason = payload.get('errors') or getattr(ex, 'reason') updated_resp_error = ClientResponseError(ex.request_info, ex.history, status=ex.status, message=reason, headers=ex.headers) raise updated_resp_error
async def raise_expectation_failed(self) -> NoReturn: raise ClientResponseError(cast(RequestInfo, None), (), status=417)
async def raise_unauthorized(self) -> NoReturn: raise ClientResponseError(cast(RequestInfo, None), (), status=401)
async def raise_forbidden(self) -> NoReturn: raise ClientResponseError(cast(RequestInfo, None), (), status=403)
async def raise_not_found(self) -> NoReturn: raise ClientResponseError(cast(RequestInfo, None), (), status=404)
async def raise_conflict(self) -> NoReturn: raise ClientResponseError(cast(RequestInfo, None), (), status=409)
async def raise_unsupported_media(self) -> NoReturn: raise ClientResponseError(cast(RequestInfo, None), (), status=415)
async def raise_custom(self) -> NoReturn: raise ClientResponseError(cast(RequestInfo, None), (), status=500)
async def raise_in_generator(self) -> AsyncGenerator[JsonDict, None]: raise ClientResponseError(cast(RequestInfo, None), (), status=400) yield None