def test_daemon_status_not_ok_connection_error(mock_monero_rpc, caplog): """Raises a requests.exceptions.ConnectionError""" mock_monero_rpc.side_effect = RequestsConnectionError( "Error when connecting.") response = daemon_rpc_status_check() assert response["status"] == DAEMON_STATUS_UNKNOWN assert response["version"] == -1 assert response["host"] == "127.0.0.1:18081" assert "error" in response assert "error" in response["error"] assert "message" in response["error"] assert response["error"]["error"] == "Error when connecting." assert (response["error"]["message"] == "Cannot determine status." ), "Wrong error." assert len(caplog.records) == 1 for record in caplog.records: assert record.levelname == "ERROR", "Wrong log message." json_message = json.loads(record.message) assert "message" in json_message, "Wrong log message." assert (json_message["message"] == "Cannot determine status." ), "Wrong log message." assert "error" in json_message, "Wrong log message." assert (json_message["error"] == "Error when connecting." ), "Wrong log message." caplog.clear()
def test_all_videos_connection_error(self, logger): exception = RequestsConnectionError('LMS is dead') responses.add(responses.GET, 'http://example.com/blocks/', body=exception) videos = self.client.all_videos('course_id') logger.warning.assert_called_with( 'Course Blocks API request failed. Is the LMS running?: %s', str(exception)) self.assertEqual(videos, None)
def blip(*_, **__): if not "uploads" in dir(FOLDER): FOLDER.uploads = 0 try: if FOLDER.uploads < numfails: # Use the exception seen from the requests package, just like # boxsdk actually does raise RequestsConnectionError() finally: FOLDER.uploads += 1 self.upload(*_, **__) return DEFAULT
def test_wait_server_close(self, mock_get): """ Tests wait_server_close """ mock_response = mock.Mock() mock_response.status_code.return_value = 200 mock_get.side_effect = mock_response with self.assertRaises(MaxRetryError): with self.assertLogs() as logs: wait_server_close("http://false", "Wait for: %ds", "") self.assertEqual( logs.output, [ "INFO:root:Wait for: 0s", "INFO:root:Wait for: 1s", "INFO:root:Wait for: 2s", "INFO:root:Wait for: 3s", "INFO:root:Wait for: 4s", "INFO:root:Wait for: 5s", "INFO:root:Wait for: 6s", "INFO:root:Wait for: 7s", "INFO:root:Wait for: 8s", "INFO:root:Wait for: 9s", ], ) mock_response = mock.Mock() mock_response.status_code.return_value = 200 mock_get.side_effect = [mock_response, RequestsConnectionError()] with self.assertLogs() as logs: wait_server_close("http://false", "Wait for: %ds", "Awaited: %ds") self.assertEqual(logs.output, ["INFO:root:Wait for: 0s", "INFO:root:Awaited: 1s"]) mock_get.side_effect = RequestsConnectionError() with self.assertLogs() as logs: wait_server_close("http://false", "Wait for: %ds", "Awaited: %ds") self.assertEqual(logs.output, ["INFO:root:Awaited: 0s"])
def test_handle_exception(self): tests = [(RequestException(), [''], "7", "7"), (ConnectTimeout(), [''], "7", "7"), (RequestsConnectionError(), [''], "7", "7"), (Exception("Any other exception"), ["Any other exception"], "8 Any other exception", "8" ), ] for exception, exp_data, exp_english, exp_code in tests: self.check_st_exception(ConnectionError, exp_data, exp_english, exp_code, self.http_client._handle_exception, func_args=(exception,))
def send_request(self, *args, **kwargs): """ Intercept connection errors which suggest that a managed host has crashed and raise an exception indicating the location of the log """ try: return super(JSHost, self).send_request(*args, **kwargs) except RequestsConnectionError as e: if (self.manager and self.has_connected and self.logfile and 'unsafe' not in kwargs): raise ProcessError( '{} appears to have crashed, you can inspect the log file at {}' .format( self.get_name(), self.logfile, )) raise six.reraise(RequestsConnectionError, RequestsConnectionError(*e.args), sys.exc_info()[2])
def _docker_build(cls, external_path): cls._check_for_support_lib_sdist(external_path) internal_path = PurePosixPath("/project") command = " ".join(cls._make_pip_command(internal_path)) LOG.debug("command is '%s'", command) volumes = { str(external_path): { "bind": str(internal_path), "mode": "rw" } } image = f"lambci/lambda:build-{cls.RUNTIME}" LOG.warning( "Starting Docker build. This may take several minutes if the " "image '%s' needs to be pulled first.", image, ) docker_client = docker.from_env() try: logs = docker_client.containers.run( image=image, command=command, auto_remove=True, volumes=volumes, stream=True, user=f"{os.geteuid()}:{os.getgid()}", ) except RequestsConnectionError as e: # it seems quite hard to reliably extract the cause from # ConnectionError. we replace it with a friendlier error message # and preserve the cause for debug traceback cause = RequestsConnectionError( "Could not connect to docker - is it running?") cause.__cause__ = e raise DownstreamError("Error running docker build") from cause except (ContainerError, ImageLoadError, APIError) as e: raise DownstreamError("Error running docker build") from e LOG.debug("Build running. Output:") for line in logs: LOG.debug(line.rstrip(b"\n").decode("utf-8"))
def test_run_error_reporting(cli_runner, monkeypatch): caught_exceptions = { APIServerPortInUseError(): ReturnCode.PORT_ALREADY_IN_USE, ConfigurationError(): ReturnCode.RAIDEN_CONFIGURATION_ERROR, ConnectTimeout(): ReturnCode.GENERIC_COMMUNICATION_ERROR, ConnectionError(): ReturnCode.GENERIC_COMMUNICATION_ERROR, EthereumNonceTooLow(): ReturnCode.ETH_ACCOUNT_ERROR, EthNodeInterfaceError(): ReturnCode.ETH_INTERFACE_ERROR, KeystoreAuthenticationError(): ReturnCode.ETH_ACCOUNT_ERROR, KeystoreFileNotFound(): ReturnCode.ETH_ACCOUNT_ERROR, RaidenUnrecoverableError(): ReturnCode.FATAL, ReplacementTransactionUnderpriced(): ReturnCode.ETH_ACCOUNT_ERROR, RequestsConnectionError(): ReturnCode.GENERIC_COMMUNICATION_ERROR, Exception(): ReturnCode.FATAL, } for exception, code in caught_exceptions.items(): monkeypatch.setattr(cli, "run_services", mock_raises(exception)) result = cli_runner(cli.run, "--accept-disclaimer") assert result.exception.code == code
def test_last_block_not_recent_connection_error(mock_time_range, mock_monero_rpc, caplog): """Raises a requests.exceptions.ConnectionError""" mock_monero_rpc.side_effect = RequestsConnectionError( "Error when connecting.") mock_time_range.return_value = (True, 12, "minutes") response = daemon_last_block_check() assert response["status"] == DAEMON_STATUS_UNKNOWN assert not response["block_recent"] assert response["block_recent_offset"] == 12 assert response["block_recent_offset_unit"] == "minutes" assert response["block_timestamp"] == "---" assert response["hash"] == "---" assert response["host"] == "127.0.0.1:18081" assert response["block_age"] == -1 assert "error" in response assert "error" in response["error"] assert "message" in response["error"] assert response["error"]["error"] == "Error when connecting." assert (response["error"]["message"] == "Cannot determine status." ), "Wrong error." assert len(caplog.records) == 1 for record in caplog.records: assert record.levelname == "ERROR", "Wrong log message." json_message = json.loads(record.message) assert "message" in json_message, "Wrong log message." assert (json_message["message"] == "Cannot determine status." ), "Wrong log message." assert "error" in json_message, "Wrong log message." assert (json_message["error"] == "Error when connecting." ), "Wrong log message." caplog.clear()
"bind": "/project", "mode": "rw" }}, stream=True, user=ANY, ) @pytest.mark.parametrize( "exception", [ lambda: ContainerError("abcde", 255, "/bin/false", "image", ""), ImageLoadError, lambda: APIError("500"), lambda: RequestsConnectionError( "Connection aborted.", ConnectionRefusedError(61, "Connection refused")), ], ) def test__docker_build_bad_path(plugin, tmp_path, exception): patch_sdist = patch.object(PythonLanguagePlugin, "_check_for_support_lib_sdist") patch_from_env = patch("rpdk.python.codegen.docker.from_env", autospec=True) with patch_sdist as mock_sdist, patch_from_env as mock_from_env: mock_run = mock_from_env.return_value.containers.run mock_run.side_effect = exception() with pytest.raises(DownstreamError): plugin._docker_build(tmp_path)
def test_task_fails_with_connection_error(self, retry, post): exc = RequestsConnectionError() post.side_effect = exc self.task('1234', 'owner/name') # pylint: disable=no-value-for-parameter retry.assert_called_with(exc=exc, max_retries=5, countdown=30)