diff --git a/.pylintrc b/.pylintrc index f6cc8803..ac822cb9 100644 --- a/.pylintrc +++ b/.pylintrc @@ -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, diff --git a/plugins/module_utils/_api/context/context.py b/plugins/module_utils/_api/context/context.py index e128af2f..bcb62a18 100644 --- a/plugins/module_utils/_api/context/context.py +++ b/plugins/module_utils/_api/context/context.py @@ -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 diff --git a/plugins/module_utils/_api/transport/sshconn.py b/plugins/module_utils/_api/transport/sshconn.py index dde4e017..5249cd2c 100644 --- a/plugins/module_utils/_api/transport/sshconn.py +++ b/plugins/module_utils/_api/transport/sshconn.py @@ -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) diff --git a/plugins/module_utils/_module_container/base.py b/plugins/module_utils/_module_container/base.py index 6b917f23..861e9b33 100644 --- a/plugins/module_utils/_module_container/base.py +++ b/plugins/module_utils/_module_container/base.py @@ -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 diff --git a/plugins/module_utils/_module_container/docker_api.py b/plugins/module_utils/_module_container/docker_api.py index 756f5e6a..1ccfa229 100644 --- a/plugins/module_utils/_module_container/docker_api.py +++ b/plugins/module_utils/_module_container/docker_api.py @@ -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 ( diff --git a/plugins/modules/docker_image.py b/plugins/modules/docker_image.py index 353f407c..ddc607b4 100644 --- a/plugins/modules/docker_image.py +++ b/plugins/modules/docker_image.py @@ -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) diff --git a/plugins/modules/docker_image_push.py b/plugins/modules/docker_image_push.py index 5a8d60c5..507fdb34 100644 --- a/plugins/modules/docker_image_push.py +++ b/plugins/modules/docker_image_push.py @@ -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 diff --git a/plugins/modules/docker_image_tag.py b/plugins/modules/docker_image_tag.py index 131b8d97..799af3f4 100644 --- a/plugins/modules/docker_image_tag.py +++ b/plugins/modules/docker_image_tag.py @@ -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}") diff --git a/plugins/modules/docker_swarm_service.py b/plugins/modules/docker_swarm_service.py index 90889390..4a451417 100644 --- a/plugins/modules/docker_swarm_service.py +++ b/plugins/modules/docker_swarm_service.py @@ -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: diff --git a/tests/unit/plugins/module_utils/_api/api/test_client.py b/tests/unit/plugins/module_utils/_api/api/test_client.py index e1bff783..c8cec7b1 100644 --- a/tests/unit/plugins/module_utils/_api/api/test_client.py +++ b/tests/unit/plugins/module_utils/_api/api/test_client.py @@ -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):