From 6aec90a41bc07e1757f28304d3c9e068245afdb9 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Thu, 11 May 2023 15:58:14 +0300 Subject: [PATCH] Fix Ruff B904s (be explicit about exception causes) Signed-off-by: Aarni Koskela --- docker/api/client.py | 14 +++++++------- docker/auth.py | 2 +- docker/context/api.py | 2 +- docker/context/context.py | 2 +- docker/credentials/store.py | 6 +++--- docker/models/containers.py | 4 ++-- docker/tls.py | 2 +- docker/transport/npipeconn.py | 7 +++---- docker/transport/sshconn.py | 6 +++--- docker/types/daemon.py | 4 ++-- docker/utils/build.py | 4 ++-- docker/utils/json_stream.py | 2 +- docker/utils/utils.py | 4 ++-- tests/unit/auth_test.py | 4 ++-- 14 files changed, 31 insertions(+), 32 deletions(-) diff --git a/docker/api/client.py b/docker/api/client.py index ce1b3a30..a2cb459d 100644 --- a/docker/api/client.py +++ b/docker/api/client.py @@ -160,10 +160,10 @@ class APIClient( base_url, timeout, pool_connections=num_pools, max_pool_size=max_pool_size ) - except NameError: + except NameError as err: raise DockerException( 'Install pypiwin32 package to enable npipe:// support' - ) + ) from err self.mount('http+docker://', self._custom_adapter) self.base_url = 'http+docker://localnpipe' elif base_url.startswith('ssh://'): @@ -172,10 +172,10 @@ class APIClient( base_url, timeout, pool_connections=num_pools, max_pool_size=max_pool_size, shell_out=use_ssh_client ) - except NameError: + except NameError as err: raise DockerException( 'Install paramiko package to enable ssh:// support' - ) + ) from err self.mount('http+docker://ssh', self._custom_adapter) self._unmount('http://', 'https://') self.base_url = 'http+docker://ssh' @@ -211,15 +211,15 @@ class APIClient( def _retrieve_server_version(self): try: return self.version(api_version=False)["ApiVersion"] - except KeyError: + except KeyError as ke: raise DockerException( 'Invalid response from docker daemon: key "ApiVersion"' ' is missing.' - ) + ) from ke except Exception as e: raise DockerException( f'Error while fetching server API version: {e}' - ) + ) from e def _set_request_timeout(self, kwargs): """Prepare the kwargs for an HTTP request by inserting the timeout diff --git a/docker/auth.py b/docker/auth.py index 4bce7887..7a301ba4 100644 --- a/docker/auth.py +++ b/docker/auth.py @@ -268,7 +268,7 @@ class AuthConfig(dict): except credentials.StoreError as e: raise errors.DockerException( f'Credentials store error: {repr(e)}' - ) + ) from e def _get_store_instance(self, name): if name not in self._stores: diff --git a/docker/context/api.py b/docker/context/api.py index e340fb6d..493f470e 100644 --- a/docker/context/api.py +++ b/docker/context/api.py @@ -114,7 +114,7 @@ class ContextAPI: except Exception as e: raise errors.ContextException( f"Failed to load metafile {filename}: {e}", - ) + ) from e contexts = [cls.DEFAULT_CONTEXT] for name in names: diff --git a/docker/context/context.py b/docker/context/context.py index b607b771..4faf8e70 100644 --- a/docker/context/context.py +++ b/docker/context/context.py @@ -99,7 +99,7 @@ class Context: # unknown format raise Exception( f"Detected corrupted meta file for context {name} : {e}" - ) + ) from e # for docker endpoints, set defaults for # Host and SkipTLSVerify fields diff --git a/docker/credentials/store.py b/docker/credentials/store.py index 37c703e7..5edeaa7f 100644 --- a/docker/credentials/store.py +++ b/docker/credentials/store.py @@ -80,14 +80,14 @@ class Store: [self.exe, subcmd], input=data_input, env=env, ) except subprocess.CalledProcessError as e: - raise errors.process_store_error(e, self.program) + raise errors.process_store_error(e, self.program) from e except OSError as e: if e.errno == errno.ENOENT: raise errors.StoreError( f'{self.program} not installed or not available in PATH' - ) + ) from e else: raise errors.StoreError( f'Unexpected OS error "{e.strerror}", errno={e.errno}' - ) + ) from e return output diff --git a/docker/models/containers.py b/docker/models/containers.py index 64838397..44bb92a0 100644 --- a/docker/models/containers.py +++ b/docker/models/containers.py @@ -47,11 +47,11 @@ class Container(Model): try: result = self.attrs['Config'].get('Labels') return result or {} - except KeyError: + except KeyError as ke: raise DockerException( 'Label data is not available for sparse objects. Call reload()' ' to retrieve all information' - ) + ) from ke @property def status(self): diff --git a/docker/tls.py b/docker/tls.py index f4dffb2e..a4dd0020 100644 --- a/docker/tls.py +++ b/docker/tls.py @@ -55,7 +55,7 @@ class TLSConfig: raise errors.TLSParameterError( 'client_cert must be a tuple of' ' (client certificate, key file)' - ) + ) from None if not (tls_cert and tls_key) or (not os.path.isfile(tls_cert) or not os.path.isfile(tls_key)): diff --git a/docker/transport/npipeconn.py b/docker/transport/npipeconn.py index 45988b2d..d335d871 100644 --- a/docker/transport/npipeconn.py +++ b/docker/transport/npipeconn.py @@ -46,9 +46,8 @@ class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): conn = None try: conn = self.pool.get(block=self.block, timeout=timeout) - - except AttributeError: # self.pool is None - raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") + except AttributeError as ae: # self.pool is None + raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") from ae except queue.Empty: if self.block: @@ -56,7 +55,7 @@ class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): self, "Pool reached maximum size and no more " "connections are allowed." - ) + ) from None # Oh well, we'll create a new connection then return conn or self._new_conn() diff --git a/docker/transport/sshconn.py b/docker/transport/sshconn.py index a92beb62..6e1d0ee7 100644 --- a/docker/transport/sshconn.py +++ b/docker/transport/sshconn.py @@ -141,8 +141,8 @@ class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool): try: conn = self.pool.get(block=self.block, timeout=timeout) - except AttributeError: # self.pool is None - raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") + except AttributeError as ae: # self.pool is None + raise urllib3.exceptions.ClosedPoolError(self, "Pool is closed.") from ae except queue.Empty: if self.block: @@ -150,7 +150,7 @@ class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool): self, "Pool reached maximum size and no more " "connections are allowed." - ) + ) from None # Oh well, we'll create a new connection then return conn or self._new_conn() diff --git a/docker/types/daemon.py b/docker/types/daemon.py index 096b2cc1..04e6ccb2 100644 --- a/docker/types/daemon.py +++ b/docker/types/daemon.py @@ -28,9 +28,9 @@ class CancellableStream: try: return next(self._stream) except urllib3.exceptions.ProtocolError: - raise StopIteration + raise StopIteration from None except OSError: - raise StopIteration + raise StopIteration from None next = __next__ diff --git a/docker/utils/build.py b/docker/utils/build.py index 6b38eacd..8d18c2be 100644 --- a/docker/utils/build.py +++ b/docker/utils/build.py @@ -93,10 +93,10 @@ def create_archive(root, files=None, fileobj=None, gzip=False, try: with open(full_path, 'rb') as f: t.addfile(i, f) - except OSError: + except OSError as oe: raise OSError( f'Can not read file in context: {full_path}' - ) + ) from oe else: # Directories, FIFOs, symlinks... don't need to be read. t.addfile(i, None) diff --git a/docker/utils/json_stream.py b/docker/utils/json_stream.py index f384175f..266193e5 100644 --- a/docker/utils/json_stream.py +++ b/docker/utils/json_stream.py @@ -72,4 +72,4 @@ def split_buffer(stream, splitter=None, decoder=lambda a: a): try: yield decoder(buffered) except Exception as e: - raise StreamParseError(e) + raise StreamParseError(e) from e diff --git a/docker/utils/utils.py b/docker/utils/utils.py index 234be320..4affeb33 100644 --- a/docker/utils/utils.py +++ b/docker/utils/utils.py @@ -414,11 +414,11 @@ def parse_bytes(s): if suffix in units.keys() or suffix.isdigit(): try: digits = float(digits_part) - except ValueError: + except ValueError as ve: raise errors.DockerException( 'Failed converting the string value for memory ' f'({digits_part}) to an integer.' - ) + ) from ve # Reconvert to long for the final result s = int(digits * units[suffix]) diff --git a/tests/unit/auth_test.py b/tests/unit/auth_test.py index 26254fad..0ed890fd 100644 --- a/tests/unit/auth_test.py +++ b/tests/unit/auth_test.py @@ -778,8 +778,8 @@ class InMemoryStore(credentials.Store): def get(self, server): try: return self.__store[server] - except KeyError: - raise credentials.errors.CredentialsNotFound() + except KeyError as ke: + raise credentials.errors.CredentialsNotFound() from ke def store(self, server, username, secret): self.__store[server] = {