diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 50c7aede83..25ecdb055e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -35,7 +35,7 @@ repos: - id: black - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.0.242 + rev: v0.0.254 hooks: - id: ruff args: ["--fix"] diff --git a/jupyter_server/auth/identity.py b/jupyter_server/auth/identity.py index aa8ab696da..d0e01fa502 100644 --- a/jupyter_server/auth/identity.py +++ b/jupyter_server/auth/identity.py @@ -520,12 +520,11 @@ def validate_security( f"{warning} and not using authentication. " "This is highly insecure and not recommended." ) - else: - if not self.auth_enabled: - app.log.warning( - "All authentication is disabled." - " Anyone who can connect to this server will be able to run code." - ) + elif not self.auth_enabled: + app.log.warning( + "All authentication is disabled." + " Anyone who can connect to this server will be able to run code." + ) def process_login_form(self, handler: JupyterHandler) -> User | None: """Process login form data diff --git a/jupyter_server/auth/login.py b/jupyter_server/auth/login.py index a99918834e..aa161302b0 100644 --- a/jupyter_server/auth/login.py +++ b/jupyter_server/auth/login.py @@ -258,12 +258,11 @@ def validate_security(cls, app, ssl_options=None): f"{warning} and not using authentication. " "This is highly insecure and not recommended." ) - else: - if not app.password and not app.token: - app.log.warning( - "All authentication is disabled." - " Anyone who can connect to this server will be able to run code." - ) + elif not app.password and not app.token: + app.log.warning( + "All authentication is disabled." + " Anyone who can connect to this server will be able to run code." + ) @classmethod def password_from_settings(cls, settings): diff --git a/jupyter_server/base/handlers.py b/jupyter_server/base/handlers.py index e7ebf0a93d..8aec2fe128 100644 --- a/jupyter_server/base/handlers.py +++ b/jupyter_server/base/handlers.py @@ -52,7 +52,7 @@ def json_sys_info(): """Get sys info as json.""" - global _sys_info_cache + global _sys_info_cache # noqa if _sys_info_cache is None: _sys_info_cache = json.dumps(get_sys_info()) return _sys_info_cache @@ -681,8 +681,8 @@ def write_error(self, status_code, **kwargs): # get the custom message, if defined try: message = exception.log_message % exception.args - except Exception: - pass # noqa + except Exception: # noqa + pass # construct the custom reason, if defined reason = getattr(exception, "reason", "") diff --git a/jupyter_server/config_manager.py b/jupyter_server/config_manager.py index 5fde2c0dcb..9f34bb33db 100644 --- a/jupyter_server/config_manager.py +++ b/jupyter_server/config_manager.py @@ -41,9 +41,8 @@ def remove_defaults(data, defaults): remove_defaults(data[key], defaults[key]) if not data[key]: # prune empty subdicts del data[key] - else: - if value == defaults[key]: - del data[key] + elif value == defaults[key]: + del data[key] class BaseJSONConfigManager(LoggingConfigurable): diff --git a/jupyter_server/extension/application.py b/jupyter_server/extension/application.py index 4a9687e507..ff12e4e04b 100644 --- a/jupyter_server/extension/application.py +++ b/jupyter_server/extension/application.py @@ -214,9 +214,9 @@ def _default_serverapp(self): if ServerApp.initialized(): try: return ServerApp.instance() - except Exception: + except Exception: # noqa # error retrieving instance, e.g. MultipleInstanceError - pass # noqa + pass # serverapp accessed before it was defined, # declare an empty one diff --git a/jupyter_server/files/handlers.py b/jupyter_server/files/handlers.py index 86359cfc41..89a8cd580d 100644 --- a/jupyter_server/files/handlers.py +++ b/jupyter_server/files/handlers.py @@ -77,11 +77,10 @@ async def get(self, path, include_body=True): self.set_header("Content-Type", "application/octet-stream") elif cur_mime is not None: self.set_header("Content-Type", cur_mime) + elif model["format"] == "base64": + self.set_header("Content-Type", "application/octet-stream") else: - if model["format"] == "base64": - self.set_header("Content-Type", "application/octet-stream") - else: - self.set_header("Content-Type", "text/plain; charset=UTF-8") + self.set_header("Content-Type", "text/plain; charset=UTF-8") if include_body: if model["format"] == "base64": diff --git a/jupyter_server/gateway/managers.py b/jupyter_server/gateway/managers.py index 275d467da0..0421e2a550 100644 --- a/jupyter_server/gateway/managers.py +++ b/jupyter_server/gateway/managers.py @@ -337,8 +337,9 @@ async def kernel_culled(self, kernel_id: str) -> bool: # typing: ignore # Note that should the redundant polling be consolidated, or replaced with an event-based # notification model, this will need to be revisited. km = self.kernel_manager.get_kernel(kernel_id) - except Exception: # Let exceptions here reflect culled kernel - pass # noqa + except Exception: # noqa + # Let exceptions here reflect culled kernel + pass return km is None diff --git a/jupyter_server/serverapp.py b/jupyter_server/serverapp.py index 27dac22316..8427703634 100644 --- a/jupyter_server/serverapp.py +++ b/jupyter_server/serverapp.py @@ -1183,14 +1183,13 @@ def _warn_deprecated_config(self, change, clsname, new_name=None): f"ServerApp.{change.name} config is deprecated in 2.0. Use {clsname}.{new_name}." ) self.config[clsname][new_name] = change.new - else: - # Deprecated config used, new config also used. - # Warn only if the values differ. - # If the values are the same, assume intentional backward-compatible config. - if self.config[clsname][new_name] != change.new: - self.log.warning( - f"Ignoring deprecated ServerApp.{change.name} config. Using {clsname}.{new_name}." - ) + # Deprecated config used, new config also used. + # Warn only if the values differ. + # If the values are the same, assume intentional backward-compatible config. + elif self.config[clsname][new_name] != change.new: + self.log.warning( + f"Ignoring deprecated ServerApp.{change.name} config. Using {clsname}.{new_name}." + ) @observe("password") def _deprecated_password(self, change): diff --git a/jupyter_server/services/contents/manager.py b/jupyter_server/services/contents/manager.py index b6ef67e1a5..b703395c25 100644 --- a/jupyter_server/services/contents/manager.py +++ b/jupyter_server/services/contents/manager.py @@ -104,7 +104,7 @@ def _validate_preferred_dir(self, proposal): if value != self.parent.preferred_dir: self.parent.preferred_dir = os.path.join(self.root_dir, *value.split("/")) except (AttributeError, TraitError): - pass # noqa + pass return value allow_hidden = Bool(False, config=True, help="Allow access to hidden files") diff --git a/jupyter_server/services/kernels/connection/channels.py b/jupyter_server/services/kernels/connection/channels.py index a927d2002b..f4e7ec978f 100644 --- a/jupyter_server/services/kernels/connection/channels.py +++ b/jupyter_server/services/kernels/connection/channels.py @@ -443,8 +443,8 @@ def disconnect(self): try: ZMQChannelsWebsocketConnection._open_sockets.remove(self) self._close_future.set_result(None) - except Exception: - pass # noqa + except Exception: # noqa + pass def handle_incoming_message(self, incoming_msg: str) -> None: """Handle incoming messages from Websocket to ZMQ Sockets.""" @@ -729,12 +729,11 @@ def _limit_rate(self, channel, msg, msg_list): # noqa ), msg["parent_header"], ) - else: - # resume once we've got some headroom below the limit - if self._iopub_msgs_exceeded and msg_rate < (0.8 * self.iopub_msg_rate_limit): - self._iopub_msgs_exceeded = False - if not self._iopub_data_exceeded: - self.log.warning("iopub messages resumed") + # resume once we've got some headroom below the limit + elif self._iopub_msgs_exceeded and msg_rate < (0.8 * self.iopub_msg_rate_limit): + self._iopub_msgs_exceeded = False + if not self._iopub_data_exceeded: + self.log.warning("iopub messages resumed") # Check the data rate if self.iopub_data_rate_limit > 0 and data_rate > self.iopub_data_rate_limit: @@ -761,12 +760,11 @@ def _limit_rate(self, channel, msg, msg_list): # noqa ), msg["parent_header"], ) - else: - # resume once we've got some headroom below the limit - if self._iopub_data_exceeded and data_rate < (0.8 * self.iopub_data_rate_limit): - self._iopub_data_exceeded = False - if not self._iopub_msgs_exceeded: - self.log.warning("iopub messages resumed") + # resume once we've got some headroom below the limit + elif self._iopub_data_exceeded and data_rate < (0.8 * self.iopub_data_rate_limit): + self._iopub_data_exceeded = False + if not self._iopub_msgs_exceeded: + self.log.warning("iopub messages resumed") # If either of the limit flags are set, do not send the message. if self._iopub_msgs_exceeded or self._iopub_data_exceeded: diff --git a/jupyter_server/services/kernels/kernelmanager.py b/jupyter_server/services/kernels/kernelmanager.py index 61903f214d..b1ca1bbfa2 100644 --- a/jupyter_server/services/kernels/kernelmanager.py +++ b/jupyter_server/services/kernels/kernelmanager.py @@ -517,7 +517,7 @@ def list_kernels(self): kernels.append(model) except (web.HTTPError, KeyError): # Probably due to a (now) non-existent kernel, continue building the list - pass # noqa + pass return kernels # override _check_kernel_id to raise 404 instead of KeyError diff --git a/jupyter_server/services/sessions/sessionmanager.py b/jupyter_server/services/sessions/sessionmanager.py index 62eed82826..dda04b82c2 100644 --- a/jupyter_server/services/sessions/sessionmanager.py +++ b/jupyter_server/services/sessions/sessionmanager.py @@ -410,7 +410,7 @@ async def get_session(self, **kwargs): raise TypeError(msg) conditions.append("%s=?" % column) - query = "SELECT * FROM session WHERE %s" % (" AND ".join(conditions)) + query = "SELECT * FROM session WHERE %s" % (" AND ".join(conditions)) # noqa self.cursor.execute(query, list(kwargs.values())) try: @@ -458,7 +458,7 @@ async def update_session(self, session_id, **kwargs): if column not in self._columns: raise TypeError("No such column: %r" % column) sets.append("%s=?" % column) - query = "UPDATE session SET %s WHERE session_id=?" % (", ".join(sets)) + query = "UPDATE session SET %s WHERE session_id=?" % (", ".join(sets)) # noqa self.cursor.execute(query, [*list(kwargs.values()), session_id]) async def kernel_culled(self, kernel_id: str) -> bool: diff --git a/jupyter_server/traittypes.py b/jupyter_server/traittypes.py index 35291804fa..33844f9324 100644 --- a/jupyter_server/traittypes.py +++ b/jupyter_server/traittypes.py @@ -76,8 +76,8 @@ def validate(self, obj, value): try: if self.subclass_from_klasses(value): return value - except Exception: - pass # noqa + except Exception: # noqa + pass self.error(obj, value) @@ -86,7 +86,7 @@ def info(self): result = "a subclass of " for klass in self.klasses: if not isinstance(klass, str): - klass = klass.__module__ + "." + klass.__name__ + klass = klass.__module__ + "." + klass.__name__ # noqa result += f"{klass} or " # Strip the last "or" result = result.strip(" or ") # noqa @@ -106,10 +106,10 @@ def _resolve_classes(self): if isinstance(klass, str): # Try importing the classes to compare. Silently, ignore if not importable. try: - klass = self._resolve_string(klass) + klass = self._resolve_string(klass) # noqa self.importable_klasses.append(klass) - except Exception: - pass # noqa + except Exception: # noqa + pass else: self.importable_klasses.append(klass) @@ -156,7 +156,7 @@ class or its subclasses. Our implementation is quite different None, the None is replaced by ``()`` or ``{}``, respectively. """ # If class - if klasses is None: + if klasses is None: # noqa self.klasses = klasses # Verify all elements are either classes or strings. elif all(inspect.isclass(k) or isinstance(k, str) for k in klasses): @@ -218,10 +218,10 @@ def _resolve_classes(self): if isinstance(klass, str): # Try importing the classes to compare. Silently, ignore if not importable. try: - klass = self._resolve_string(klass) + klass = self._resolve_string(klass) # noqa self.importable_klasses.append(klass) - except Exception: - pass # noqa + except Exception: # noqa + pass else: self.importable_klasses.append(klass) diff --git a/jupyter_server/utils.py b/jupyter_server/utils.py index 67f3baa556..7127336ff1 100644 --- a/jupyter_server/utils.py +++ b/jupyter_server/utils.py @@ -369,7 +369,7 @@ def filefind(filename, path_dirs=None): for path in path_dirs: if path == ".": - path = os.getcwd() + path = os.getcwd() # noqa testname = expand_path(os.path.join(path, filename)) if os.path.isfile(testname): return os.path.abspath(testname) diff --git a/pyproject.toml b/pyproject.toml index 403d530358..1631be6ba5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -123,7 +123,7 @@ detached = true dependencies = [ "black[jupyter]==23.1.0", "mdformat>0.7", - "ruff==0.0.242", + "ruff==0.0.254", ] [tool.hatch.envs.lint.scripts] style = [ diff --git a/tests/conftest.py b/tests/conftest.py index 5964a37352..9b43e0f532 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -33,11 +33,10 @@ def pytest_runtest_setup(item): if item.config.getoption("--integration_tests") is True: if not is_integration_test: pytest.skip("Only running tests marked as 'integration_test'.") - else: - if is_integration_test: - pytest.skip( - "Skipping this test because it's marked 'integration_test'. Run integration tests using the `--integration_tests` flag." - ) + elif is_integration_test: + pytest.skip( + "Skipping this test because it's marked 'integration_test'. Run integration tests using the `--integration_tests` flag." + ) mock_html = """ diff --git a/tests/services/contents/test_fileio.py b/tests/services/contents/test_fileio.py index a1826cfe82..9133454724 100644 --- a/tests/services/contents/test_fileio.py +++ b/tests/services/contents/test_fileio.py @@ -69,7 +69,7 @@ class CustomExc(Exception): @pytest.fixture def handle_umask(): - global umask + global umask # noqa umask = os.umask(0) os.umask(umask) yield