Address broad-exception-raised.

This commit is contained in:
Felix Fontein 2025-10-11 14:14:58 +02:00
parent 0fa1dacbbd
commit 451e235c2a
10 changed files with 29 additions and 30 deletions

View File

@ -382,7 +382,6 @@ disable=raw-checker-failed,
abstract-method,
arguments-differ,
broad-exception-caught,
broad-exception-raised,
consider-iterating-dictionary,
consider-using-dict-comprehension,
consider-using-f-string,

View File

@ -42,7 +42,7 @@ class Context:
description=None,
):
if not name:
raise Exception("Name not provided")
raise ValueError("Name not provided")
self.name = name
self.context_type = None
self.orchestrator = orchestrator
@ -136,7 +136,7 @@ class Context:
metadata = json.load(f)
except (OSError, KeyError, ValueError) as e:
# unknown format
raise Exception(
raise RuntimeError(
f"Detected corrupted meta file for context {name} : {e}"
) from e

View File

@ -82,7 +82,7 @@ class SSHSocket(socket.socket):
def _write(self, data):
if not self.proc or self.proc.stdin.closed:
raise Exception(
raise RuntimeError(
"SSH subprocess not initiated. connect() must be called first."
)
written = self.proc.stdin.write(data)
@ -97,7 +97,7 @@ class SSHSocket(socket.socket):
def recv(self, n):
if not self.proc:
raise Exception(
raise RuntimeError(
"SSH subprocess not initiated. connect() must be called first."
)
return self.proc.stdout.read(n)

View File

@ -58,7 +58,7 @@ def _get_ansible_type(value_type):
if value_type == "set":
return "list"
if value_type not in ("list", "dict", "bool", "int", "float", "str"):
raise Exception(f'Invalid type "{value_type}"')
raise ValueError(f'Invalid type "{value_type}"')
return value_type
@ -87,13 +87,13 @@ class Option:
needs_elements = self.value_type in ("list", "set")
needs_ansible_elements = self.ansible_type in ("list",)
if elements is not None and not needs_elements:
raise Exception("elements only allowed for lists/sets")
raise ValueError("elements only allowed for lists/sets")
if elements is None and needs_elements:
raise Exception("elements required for lists/sets")
raise ValueError("elements required for lists/sets")
if ansible_elements is not None and not needs_ansible_elements:
raise Exception("Ansible elements only allowed for Ansible lists")
raise ValueError("Ansible elements only allowed for Ansible lists")
if (elements is None and ansible_elements is None) and needs_ansible_elements:
raise Exception("Ansible elements required for Ansible lists")
raise ValueError("Ansible elements required for Ansible lists")
self.elements = elements if needs_elements else None
self.ansible_elements = (
(ansible_elements or _get_ansible_type(elements))
@ -104,7 +104,7 @@ class Option:
self.ansible_type == "list" and self.ansible_elements == "dict"
) or (self.ansible_type == "dict")
if ansible_suboptions is not None and not needs_suboptions:
raise Exception(
raise ValueError(
"suboptions only allowed for Ansible lists with dicts, or Ansible dicts"
)
if (
@ -113,7 +113,7 @@ class Option:
and not needs_no_suboptions
and not not_an_ansible_option
):
raise Exception(
raise ValueError(
"suboptions required for Ansible lists with dicts, or Ansible dicts"
)
self.ansible_suboptions = ansible_suboptions if needs_suboptions else None

View File

@ -124,7 +124,7 @@ def _get_ansible_type(our_type):
if our_type == "set":
return "list"
if our_type not in ("list", "dict", "bool", "int", "float", "str"):
raise Exception(f'Invalid type "{our_type}"')
raise ValueError(f'Invalid type "{our_type}"')
return our_type
@ -266,7 +266,7 @@ class DockerAPIEngineDriver(EngineDriver):
# Ensure driver_opts values are strings
for key, val in value.items():
if not isinstance(val, str):
raise Exception(
raise ValueError(
f"driver_opts values must be strings, got {type(val).__name__} for key '{key}'"
)
params[dest_para] = value
@ -278,7 +278,7 @@ class DockerAPIEngineDriver(EngineDriver):
params[dest_para] = value
if parameters:
ups = ", ".join([f'"{p}"' for p in sorted(parameters)])
raise Exception(
raise ValueError(
f"Unknown parameter(s) for connect_container_to_network for Docker API driver: {ups}"
)
ipam_config = {}
@ -399,13 +399,13 @@ class DockerAPIEngineDriver(EngineDriver):
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we do not end up in an infinite loop.
if count == 3:
raise Exception(f"{exc} [tried to unpause three times]")
raise RuntimeError(f"{exc} [tried to unpause three times]")
count += 1
# Unpause
try:
self.unpause_container(client, container_id)
except Exception as exc2:
raise Exception(f"{exc2} [while unpausing]")
raise RuntimeError(f"{exc2} [while unpausing]")
# Now try again
continue
raise
@ -430,13 +430,13 @@ class DockerAPIEngineDriver(EngineDriver):
# New docker daemon versions do not allow containers to be removed
# if they are paused. Make sure we do not end up in an infinite loop.
if count == 3:
raise Exception(f"{exc} [tried to unpause three times]")
raise RuntimeError(f"{exc} [tried to unpause three times]")
count += 1
# Unpause
try:
self.unpause_container(client, container_id)
except Exception as exc2:
raise Exception(f"{exc2} [while unpausing]")
raise RuntimeError(f"{exc2} [while unpausing]")
# Now try again
continue
if (

View File

@ -779,7 +779,7 @@ class ImageManager(DockerBaseClass):
for line in self.client._stream_helper(response, decode=True):
self.log(line, pretty_print=True)
if line.get("errorDetail"):
raise Exception(line["errorDetail"]["message"])
raise RuntimeError(line["errorDetail"]["message"])
status = line.get("status")
if status == "Pushing":
changed = True
@ -842,7 +842,7 @@ class ImageManager(DockerBaseClass):
)
self.client._raise_for_status(res)
if res.status_code != 201:
raise Exception("Tag operation failed.")
raise RuntimeError("Tag operation failed.")
except Exception as exc:
self.fail(f"Error: failed to tag image - {exc}")
self.results["image"] = self.client.find_image(name=repo, tag=repo_tag)

View File

@ -155,7 +155,7 @@ class ImagePusher(DockerBaseClass):
for line in self.client._stream_helper(response, decode=True):
self.log(line, pretty_print=True)
if line.get("errorDetail"):
raise Exception(line["errorDetail"]["message"])
raise RuntimeError(line["errorDetail"]["message"])
status = line.get("status")
if status == "Pushing":
results["changed"] = True

View File

@ -214,7 +214,7 @@ class ImageTagger(DockerBaseClass):
)
self.client._raise_for_status(res)
if res.status_code != 201:
raise Exception("Tag operation failed.")
raise RuntimeError("Tag operation failed.")
except Exception as exc:
self.fail(f"Error: failed to tag image as {name}:{tag} - {exc}")

View File

@ -1046,7 +1046,7 @@ def has_list_changed(new_list, old_list, sort_lists=True, sort_key=None):
if unsorted_list and isinstance(unsorted_list[0], dict):
if not sort_key:
raise Exception("A sort key was not specified when sorting list")
raise ValueError("A sort key was not specified when sorting list")
else:
return sorted(unsorted_list, key=lambda k: k[sort_key])
@ -1374,7 +1374,7 @@ class DockerService(DockerBaseClass):
try:
memory = human_to_bytes(memory)
except ValueError as exc:
raise Exception(f"Failed to convert limit_memory to bytes: {exc}")
raise ValueError(f"Failed to convert limit_memory to bytes: {exc}")
return {
"limit_cpu": cpus,
"limit_memory": memory,
@ -1396,7 +1396,7 @@ class DockerService(DockerBaseClass):
try:
memory = human_to_bytes(memory)
except ValueError as exc:
raise Exception(f"Failed to convert reserve_memory to bytes: {exc}")
raise ValueError(f"Failed to convert reserve_memory to bytes: {exc}")
return {
"reserve_cpu": cpus,
"reserve_memory": memory,
@ -1470,7 +1470,7 @@ class DockerService(DockerBaseClass):
for index, item in invalid_items
]
)
raise Exception(
raise ValueError(
"All items in a command list need to be strings. "
f"Check quoting. Invalid items: {errors}."
)
@ -2339,7 +2339,7 @@ class DockerServiceManager:
ds.mode = to_text("replicated-job", encoding="utf-8")
ds.replicas = mode["ReplicatedJob"]["TotalCompletions"]
else:
raise Exception(f"Unknown service mode: {mode}")
raise ValueError(f"Unknown service mode: {mode}")
raw_data_mounts = task_template_data["ContainerSpec"].get("Mounts")
if raw_data_mounts:

View File

@ -87,7 +87,7 @@ def fake_resp(method, url, *args, **kwargs):
elif (url, method) in fake_api.fake_responses:
key = (url, method)
if not key:
raise Exception(f"{method} {url}")
raise NotImplementedError(f"{method} {url}")
status_code, content = fake_api.fake_responses[key]()
return response(status_code=status_code, content=content)
@ -506,7 +506,7 @@ class TCPSocketStreamTest(unittest.TestCase):
data += stderr_data
return data
else:
raise Exception(f"Unknown path {path}")
raise NotImplementedError(f"Unknown path {path}")
@staticmethod
def frame_header(stream, data):