ansible-test - Use raise from to handle exceptions (#80905)

pull/80911/head
Matt Clay 1 year ago committed by GitHub
parent 43c31c5dc2
commit 3a1d58bc58
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,2 @@
bugfixes:
- ansible-test - Use ``raise ... from ...`` when raising exceptions from within an exception handler.

@ -70,7 +70,7 @@ class AzurePipelines(CIProvider):
os.environ['SYSTEM_JOBIDENTIFIER'],
)
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0])
raise MissingEnvironmentVariable(name=ex.args[0]) from None
return prefix
@ -121,7 +121,7 @@ class AzurePipelines(CIProvider):
task_id=str(uuid.UUID(os.environ['SYSTEM_TASKINSTANCEID'])),
)
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0])
raise MissingEnvironmentVariable(name=ex.args[0]) from None
self.auth.sign_request(request)
@ -154,7 +154,7 @@ class AzurePipelinesAuthHelper(CryptographyAuthHelper):
try:
agent_temp_directory = os.environ['AGENT_TEMPDIRECTORY']
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0])
raise MissingEnvironmentVariable(name=ex.args[0]) from None
# the temporary file cannot be deleted because we do not know when the agent has processed it
# placing the file in the agent's temp directory allows it to be picked up when the job is running in a container
@ -181,7 +181,7 @@ class AzurePipelinesChanges:
self.source_branch_name = os.environ['BUILD_SOURCEBRANCHNAME']
self.pr_branch_name = os.environ.get('SYSTEM_PULLREQUEST_TARGETBRANCH')
except KeyError as ex:
raise MissingEnvironmentVariable(name=ex.args[0])
raise MissingEnvironmentVariable(name=ex.args[0]) from None
if self.source_branch.startswith('refs/tags/'):
raise ChangeDetectionNotSupported('Change detection is not supported for tags.')

@ -57,9 +57,9 @@ def load_report(report: dict[str, t.Any]) -> tuple[list[str], Arcs, Lines]:
arc_data: dict[str, dict[str, int]] = report['arcs']
line_data: dict[str, dict[int, int]] = report['lines']
except KeyError as ex:
raise ApplicationError('Document is missing key "%s".' % ex.args)
raise ApplicationError('Document is missing key "%s".' % ex.args) from None
except TypeError:
raise ApplicationError('Document is type "%s" instead of "dict".' % type(report).__name__)
raise ApplicationError('Document is type "%s" instead of "dict".' % type(report).__name__) from None
arcs = dict((path, dict((parse_arc(arc), set(target_sets[index])) for arc, index in data.items())) for path, data in arc_data.items())
lines = dict((path, dict((int(line), set(target_sets[index])) for line, index in data.items())) for path, data in line_data.items())
@ -72,12 +72,12 @@ def read_report(path: str) -> tuple[list[str], Arcs, Lines]:
try:
report = read_json_file(path)
except Exception as ex:
raise ApplicationError('File "%s" is not valid JSON: %s' % (path, ex))
raise ApplicationError('File "%s" is not valid JSON: %s' % (path, ex)) from None
try:
return load_report(report)
except ApplicationError as ex:
raise ApplicationError('File "%s" is not an aggregated coverage data file. %s' % (path, ex))
raise ApplicationError('File "%s" is not an aggregated coverage data file. %s' % (path, ex)) from None
def write_report(args: CoverageAnalyzeTargetsConfig, report: dict[str, t.Any], path: str) -> None:

@ -143,7 +143,7 @@ class DiffParser:
traceback.format_exc(),
)
raise ApplicationError(message.strip())
raise ApplicationError(message.strip()) from None
self.previous_line = self.line

@ -126,7 +126,7 @@ class HttpResponse:
try:
return json.loads(self.response)
except ValueError:
raise HttpError(self.status_code, 'Cannot parse response to %s %s as JSON:\n%s' % (self.method, self.url, self.response))
raise HttpError(self.status_code, 'Cannot parse response to %s %s as JSON:\n%s' % (self.method, self.url, self.response)) from None
class HttpError(ApplicationError):

@ -290,7 +290,7 @@ def run_pip(
connection.run([python.path], data=script, capture=True)
except SubprocessError as ex:
if 'pip is unavailable:' in ex.stdout + ex.stderr:
raise PipUnavailableError(python)
raise PipUnavailableError(python) from None
raise

@ -7,7 +7,6 @@ disable=
deprecated-module, # results vary by Python version
duplicate-code, # consistent results require running with --jobs 1 and testing all files
import-outside-toplevel, # common pattern in ansible related code
raise-missing-from, # Python 2.x does not support raise from
broad-exception-raised, # many exceptions with no need for a custom type
too-few-public-methods,
too-many-public-methods,

@ -129,7 +129,7 @@ def parse_isodate(value):
try:
return datetime.datetime.strptime(value, '%Y-%m-%d').date()
except ValueError:
raise ValueError(msg)
raise ValueError(msg) from None
class AnsibleDeprecatedChecker(BaseChecker):

@ -50,7 +50,7 @@ def read_manifest_json(collection_path):
)
validate_version(result['version'])
except Exception as ex: # pylint: disable=broad-except
raise Exception('{0}: {1}'.format(os.path.basename(manifest_path), ex))
raise Exception('{0}: {1}'.format(os.path.basename(manifest_path), ex)) from None
return result
@ -71,7 +71,7 @@ def read_galaxy_yml(collection_path):
)
validate_version(result['version'])
except Exception as ex: # pylint: disable=broad-except
raise Exception('{0}: {1}'.format(os.path.basename(galaxy_path), ex))
raise Exception('{0}: {1}'.format(os.path.basename(galaxy_path), ex)) from None
return result

Loading…
Cancel
Save