Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle flake8-errmsg #1155

Merged
merged 2 commits into from
Dec 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions jupyter_server/auth/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ def fill_defaults(self):

# username is the only truly required field
if not self.username:
raise ValueError(f"user.username must not be empty: {self}")
msg = f"user.username must not be empty: {self}"
raise ValueError(msg)

# derive name fields from username -> name -> display name
if not self.name:
Expand Down Expand Up @@ -103,10 +104,12 @@ def _backward_compat_user(got_user: Any) -> User:
kwargs[field] = got_user[field]
try:
return User(**kwargs)
except TypeError as e:
raise ValueError(f"Unrecognized user: {got_user}") from e
except TypeError:
msg = f"Unrecognized user: {got_user}"
raise ValueError(msg) from None
else:
raise ValueError(f"Unrecognized user: {got_user}")
msg = f"Unrecognized user: {got_user}"
raise ValueError(msg)


class IdentityProvider(LoggingConfigurable):
Expand Down
3 changes: 2 additions & 1 deletion jupyter_server/auth/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ def passwd(passphrase=None, algorithm="argon2"):
else:
warnings.warn("Passwords do not match.")
else:
raise ValueError("No matching passwords found. Giving up.")
msg = "No matching passwords found. Giving up."
raise ValueError(msg)

if algorithm == "argon2":
import argon2
Expand Down
5 changes: 3 additions & 2 deletions jupyter_server/extension/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,11 @@ def static_url(self, path, include_host=None, **kwargs):
self.require_setting(key, "static_url") # type:ignore[attr-defined]
except Exception as e:
if key in self.settings: # type:ignore[attr-defined]
raise Exception(
msg = (
"This extension doesn't have any static paths listed. Check that the "
"extension's `static_paths` trait is set."
) from e
)
raise Exception(msg) from None
else:
raise e

Expand Down
27 changes: 14 additions & 13 deletions jupyter_server/extension/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,18 @@ def _valid_metadata(self, proposed):
# Verify that the metadata has a "name" key.
try:
self._module_name = metadata["module"]
except KeyError as e:
raise ExtensionMetadataError(
"There is no 'module' key in the extension's metadata packet."
) from e
except KeyError:
msg = "There is no 'module' key in the extension's metadata packet."
raise ExtensionMetadataError(msg) from None

try:
self._module = importlib.import_module(self._module_name)
except ImportError as e:
raise ExtensionModuleNotFound(
"The submodule '{}' could not be found. Are you "
"sure the extension is installed?".format(self._module_name)
) from e
except ImportError:
msg = (
f"The submodule '{self._module_name}' could not be found. Are you "
"sure the extension is installed?"
)
raise ExtensionModuleNotFound(msg) from None
# If the metadata includes an ExtensionApp, create an instance.
if "app" in metadata:
self._app = metadata["app"]()
Expand Down Expand Up @@ -174,10 +174,11 @@ def _validate_name(self, proposed):
try:
self._module, self._metadata = get_metadata(name)
except ImportError as e:
raise ExtensionModuleNotFound(
"The module '{name}' could not be found ({e}). Are you "
"sure the extension is installed?".format(name=name, e=e)
) from e
msg = (
f"The module '{name}' could not be found ({e}). Are you "
"sure the extension is installed?"
)
raise ExtensionModuleNotFound(msg) from None
# Create extension point interfaces for each extension path.
for m in self._metadata:
point = ExtensionPoint(metadata=m)
Expand Down
3 changes: 2 additions & 1 deletion jupyter_server/extension/serverextension.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,8 @@ def list_server_extensions(self):
self.log.info(f" - Validating {name}...")
extension = ExtensionPackage(name=name, enabled=enabled)
if not extension.validate():
raise ValueError("validation failed")
msg = "validation failed"
raise ValueError(msg)
version = extension.version
self.log.info(f" {name} {version} {GREEN_OK}")
except Exception as err:
Expand Down
5 changes: 3 additions & 2 deletions jupyter_server/extension/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ def get_loader(obj, logger=None):
"of Jupyter Server.".format(name=obj),
DeprecationWarning,
)
except Exception as e:
raise ExtensionLoadingError("_load_jupyter_server_extension function was not found.") from e
except Exception:
msg = "_load_jupyter_server_extension function was not found."
raise ExtensionLoadingError(msg) from None
return func


Expand Down
16 changes: 7 additions & 9 deletions jupyter_server/gateway/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,12 +283,8 @@ async def get_kernel_spec(self, kernel_name, **kwargs):
if error.status_code == 404:
# Convert not found to KeyError since that's what the Notebook handler expects
# message is not used, but might as well make it useful for troubleshooting
raise KeyError(
"kernelspec {kernel_name} not found on Gateway server at: {gateway_url}".format(
kernel_name=kernel_name,
gateway_url=GatewayClient.instance().url,
)
) from error
msg = f"kernelspec {kernel_name} not found on Gateway server at: {GatewayClient.instance().url}"
raise KeyError(msg) from None
else:
raise
else:
Expand Down Expand Up @@ -565,15 +561,17 @@ async def _async_get(self, timeout=None):
if timeout is None:
timeout = float("inf")
elif timeout < 0:
raise ValueError("'timeout' must be a non-negative number")
msg = "'timeout' must be a non-negative number"
raise ValueError(msg)
end_time = monotonic() + timeout

while True:
try:
return self.get(block=False)
except Empty as e:
except Empty:
if self.response_router_finished:
raise RuntimeError("Response router had finished") from e
msg = "Response router had finished"
raise RuntimeError(msg) from None
if monotonic() > end_time:
raise
await asyncio.sleep(0)
Expand Down
17 changes: 10 additions & 7 deletions jupyter_server/serverapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,12 +419,13 @@ def init_handlers(self, default_services, settings):
for loc in locations:
handlers.extend(load_handlers(loc))
else:
raise Exception(
"{} is not recognized as a jupyter_server "
msg = (
f"{service} is not recognized as a jupyter_server "
"service. If this is a custom service, "
"try adding it to the "
"`extra_services` list.".format(service)
"`extra_services` list."
)
raise Exception(msg)

# Add extra handlers from contents manager.
handlers.extend(settings["contents_manager"].get_extra_handlers())
Expand Down Expand Up @@ -2375,23 +2376,25 @@ def http_server(self):
"""An instance of Tornado's HTTPServer class for the Server Web Application."""
try:
return self._http_server
except AttributeError as e:
raise AttributeError(
except AttributeError:
msg = (
"An HTTPServer instance has not been created for the "
"Server Web Application. To create an HTTPServer for this "
"application, call `.init_httpserver()`."
) from e
)
raise AttributeError(msg) from None

def init_httpserver(self):
"""Creates an instance of a Tornado HTTPServer for the Server Web Application
and sets the http_server attribute.
"""
# Check that a web_app has been initialized before starting a server.
if not hasattr(self, "web_app"):
raise AttributeError(
msg = (
"A tornado web application has not be initialized. "
"Try calling `.init_webapp()` first."
)
raise AttributeError(msg)

# Create an instance of the server.
self._http_server = httpserver.HTTPServer(
Expand Down
36 changes: 18 additions & 18 deletions jupyter_server/services/contents/checkpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,23 +22,23 @@ class Checkpoints(LoggingConfigurable):

def create_checkpoint(self, contents_mgr, path):
"""Create a checkpoint."""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def restore_checkpoint(self, contents_mgr, checkpoint_id, path):
"""Restore a checkpoint"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def rename_checkpoint(self, checkpoint_id, old_path, new_path):
"""Rename a single checkpoint from old_path to new_path."""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def delete_checkpoint(self, checkpoint_id, path):
"""delete a checkpoint for a file"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def list_checkpoints(self, path):
"""Return a list of checkpoints for a given file"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def rename_all_checkpoints(self, old_path, new_path):
"""Rename all checkpoints for old_path to new_path."""
Expand Down Expand Up @@ -107,14 +107,14 @@ def create_file_checkpoint(self, content, format, path):

Returns a checkpoint model for the new checkpoint.
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def create_notebook_checkpoint(self, nb, path):
"""Create a checkpoint of the current state of a file

Returns a checkpoint model for the new checkpoint.
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def get_file_checkpoint(self, checkpoint_id, path):
"""Get the content of a checkpoint for a non-notebook file.
Expand All @@ -126,7 +126,7 @@ def get_file_checkpoint(self, checkpoint_id, path):
'format': {'text','base64'},
}
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

def get_notebook_checkpoint(self, checkpoint_id, path):
"""Get the content of a checkpoint for a notebook.
Expand All @@ -137,7 +137,7 @@ def get_notebook_checkpoint(self, checkpoint_id, path):
'content': <output of nbformat.read>,
}
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError


class AsyncCheckpoints(Checkpoints):
Expand All @@ -147,23 +147,23 @@ class AsyncCheckpoints(Checkpoints):

async def create_checkpoint(self, contents_mgr, path):
"""Create a checkpoint."""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def restore_checkpoint(self, contents_mgr, checkpoint_id, path):
"""Restore a checkpoint"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def rename_checkpoint(self, checkpoint_id, old_path, new_path):
"""Rename a single checkpoint from old_path to new_path."""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def delete_checkpoint(self, checkpoint_id, path):
"""delete a checkpoint for a file"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def list_checkpoints(self, path):
"""Return a list of checkpoints for a given file"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def rename_all_checkpoints(self, old_path, new_path):
"""Rename all checkpoints for old_path to new_path."""
Expand Down Expand Up @@ -217,14 +217,14 @@ async def create_file_checkpoint(self, content, format, path):

Returns a checkpoint model for the new checkpoint.
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def create_notebook_checkpoint(self, nb, path):
"""Create a checkpoint of the current state of a file

Returns a checkpoint model for the new checkpoint.
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def get_file_checkpoint(self, checkpoint_id, path):
"""Get the content of a checkpoint for a non-notebook file.
Expand All @@ -236,7 +236,7 @@ async def get_file_checkpoint(self, checkpoint_id, path):
'format': {'text','base64'},
}
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError

async def get_notebook_checkpoint(self, checkpoint_id, path):
"""Get the content of a checkpoint for a notebook.
Expand All @@ -247,4 +247,4 @@ async def get_notebook_checkpoint(self, checkpoint_id, path):
'content': <output of nbformat.read>,
}
"""
raise NotImplementedError("must be implemented in a subclass")
raise NotImplementedError
Loading