From bc964fe7ace5bdba9c41e89b592cde9978d59efe Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 26 Aug 2023 06:06:48 -0500 Subject: [PATCH] chore(ruff): Run automated fixes (97 errors) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - conftest.py: 1 × I001 (unsorted-imports) - docs/_ext/aafig.py: 5 × C408 (unnecessary-collection-call) 1 × RUF005 (collection-literal-concatenation) - docs/conf.py: 2 × C408 (unnecessary-collection-call) 1 × I001 (unsorted-imports) 1 × SIM108 (if-else-block-instead-of-if-exp) 1 × RUF100 (unused-noqa) - src/tmuxp/cli/debug_info.py: 1 × I001 (unsorted-imports) 1 × C417 (unnecessary-map) - src/tmuxp/cli/freeze.py: 1 × I001 (unsorted-imports) - src/tmuxp/cli/load.py: 1 × I001 (unsorted-imports) 1 × UP031 (printf-string-formatting) 1 × UP032 (f-string) - src/tmuxp/cli/shell.py: 1 × RUF100 (unused-noqa) - src/tmuxp/cli/utils.py: 1 × UP031 (printf-string-formatting) 1 × UP032 (f-string) - src/tmuxp/exc.py: 1 × UP032 (f-string) - src/tmuxp/shell.py: 4 × RUF100 (unused-noqa) - src/tmuxp/types.py: 1 × RUF100 (unused-noqa) - src/tmuxp/util.py: 2 × RUF100 (unused-noqa) 1 × RUF015 (unnecessary-iterable-allocation-for-first-element) 1 × TRY201 (verbose-raise) - src/tmuxp/workspace/builder.py: 3 × SIM401 (if-else-block-instead-of-dict-get) 1 × F841 (unused-variable) 1 × B006 (mutable-argument-default) 1 × RUF013 (implicit-optional) 1 × TRY201 (verbose-raise) - src/tmuxp/workspace/finders.py: 2 × B006 (mutable-argument-default) 1 × RUF013 (implicit-optional) - src/tmuxp/workspace/freezer.py: 1 × I001 (unsorted-imports) 1 × UP018 (native-literals) - src/tmuxp/workspace/importers.py: 2 × B007 (unused-loop-control-variable) 1 × SIM401 (if-else-block-instead-of-dict-get) - src/tmuxp/workspace/loader.py: 2 × SIM401 (if-else-block-instead-of-dict-get) 1 × UP018 (native-literals) 1 × SIM102 (collapsible-if) - src/tmuxp/workspace/validation.py: 1 × SIM102 (collapsible-if) - tests/cli/test_cli.py: 2 × I001 (unsorted-imports) 2 × SIM105 (suppressible-exception) 1 × PTH201 (path-constructor-current-directory) - tests/cli/test_convert.py: 2 × SIM105 (suppressible-exception) 1 × I001 (unsorted-imports) - tests/cli/test_freeze.py: 2 × I001 (unsorted-imports) 2 × SIM105 (suppressible-exception) 2 × RUF005 (collection-literal-concatenation) - tests/cli/test_import.py: 2 × SIM105 (suppressible-exception) 1 × I001 (unsorted-imports) - tests/cli/test_load.py: 5 × SIM105 (suppressible-exception) 2 × I001 (unsorted-imports) 1 × RUF005 (collection-literal-concatenation) 1 × UP032 (f-string) - tests/cli/test_ls.py: 1 × SIM105 (suppressible-exception) 1 × I001 (unsorted-imports) - tests/cli/test_shell.py: 3 × C408 (unnecessary-collection-call) 2 × I001 (unsorted-imports) 1 × SIM105 (suppressible-exception) - tests/fixtures/__init__.py: 1 × RUF100 (unused-noqa) - tests/fixtures/import_teamocil/__init__.py: 1 × RUF100 (unused-noqa) - tests/fixtures/import_tmuxinator/__init__.py: 1 × RUF100 (unused-noqa) - tests/fixtures/workspace/__init__.py: 1 × RUF100 (unused-noqa) - tests/tests/test_helpers.py: 1 × I001 (unsorted-imports) - tests/workspace/test_builder.py: 1 × I001 (unsorted-imports) 1 × SIM300 (yoda-conditions) 1 × SIM108 (if-else-block-instead-of-if-exp) 1 × UP030 (format-literals) 1 × UP032 (f-string) - tests/workspace/test_config.py: 2 × B007 (unused-loop-control-variable) --- conftest.py | 3 +- docs/_ext/aafig.py | 28 ++++++------ docs/conf.py | 13 +++--- src/tmuxp/cli/debug_info.py | 3 +- src/tmuxp/cli/freeze.py | 1 + src/tmuxp/cli/load.py | 8 ++-- src/tmuxp/cli/shell.py | 2 +- src/tmuxp/cli/utils.py | 2 +- src/tmuxp/exc.py | 8 ++-- src/tmuxp/shell.py | 8 ++-- src/tmuxp/types.py | 2 +- src/tmuxp/util.py | 8 ++-- src/tmuxp/workspace/builder.py | 23 ++++------ src/tmuxp/workspace/finders.py | 12 ++--- src/tmuxp/workspace/freezer.py | 5 ++- src/tmuxp/workspace/importers.py | 9 ++-- src/tmuxp/workspace/loader.py | 17 +++----- src/tmuxp/workspace/validation.py | 5 +-- tests/cli/test_cli.py | 17 ++++---- tests/cli/test_convert.py | 11 +++-- tests/cli/test_freeze.py | 17 ++++---- tests/cli/test_import.py | 11 +++-- tests/cli/test_load.py | 41 ++++++++--------- tests/cli/test_ls.py | 6 +-- tests/cli/test_shell.py | 46 ++++++++++---------- tests/fixtures/__init__.py | 2 +- tests/fixtures/import_teamocil/__init__.py | 2 +- tests/fixtures/import_tmuxinator/__init__.py | 2 +- tests/fixtures/workspace/__init__.py | 2 +- tests/tests/test_helpers.py | 1 - tests/workspace/test_builder.py | 13 +++--- tests/workspace/test_config.py | 2 +- 32 files changed, 146 insertions(+), 184 deletions(-) diff --git a/conftest.py b/conftest.py index a488b61a38..aa132bb30b 100644 --- a/conftest.py +++ b/conftest.py @@ -10,10 +10,9 @@ import typing as t import pytest - from _pytest.doctest import DoctestItem - from libtmux.test import namer + from tests.fixtures import utils as test_utils from tmuxp.workspace.finders import get_workspace_dir diff --git a/docs/_ext/aafig.py b/docs/_ext/aafig.py index 91a37a66b6..5759efc90c 100644 --- a/docs/_ext/aafig.py +++ b/docs/_ext/aafig.py @@ -28,7 +28,7 @@ logger = logging.getLogger(__name__) -DEFAULT_FORMATS = dict(html="svg", latex="pdf", text=None) +DEFAULT_FORMATS = {"html": "svg", "latex": "pdf", "text": None} def merge_dict(dst, src): @@ -58,21 +58,21 @@ class AafigDirective(images.Image): has_content = True required_arguments = 0 - own_option_spec = dict( - line_width=float, - background=str, - foreground=str, - fill=str, - aspect=nonnegative_int, - textual=flag, - proportional=flag, - ) + own_option_spec = { + "line_width": float, + "background": str, + "foreground": str, + "fill": str, + "aspect": nonnegative_int, + "textual": flag, + "proportional": flag, + } option_spec = images.Image.option_spec.copy() option_spec.update(own_option_spec) def run(self): - aafig_options = dict() - own_options_keys = [self.own_option_spec.keys()] + ["scale"] + aafig_options = {} + own_options_keys = [self.own_option_spec.keys(), "scale"] for (k, v) in self.options.items(): if k in own_options_keys: # convert flags to booleans @@ -88,7 +88,7 @@ def run(self): if isinstance(image_node, nodes.system_message): return [image_node] text = "\n".join(self.content) - image_node.aafig = dict(options=aafig_options, text=text) + image_node.aafig = {"options": aafig_options, "text": text} return [image_node] @@ -206,7 +206,7 @@ def setup(app): app.add_directive("aafig", AafigDirective) app.connect("doctree-read", render_aafig_images) app.add_config_value("aafig_format", DEFAULT_FORMATS, "html") - app.add_config_value("aafig_default_options", dict(), "html") + app.add_config_value("aafig_default_options", {}, "html") # vim: set expandtab shiftwidth=4 softtabstop=4 : diff --git a/docs/conf.py b/docs/conf.py index 083e01c36a..919685e38c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,10 +1,10 @@ # flake8: NOQA: E501 import contextlib import inspect +import pathlib import sys import typing as t from os.path import relpath -import pathlib import tmuxp @@ -172,12 +172,12 @@ } # aafig format, try to get working with pdf -aafig_format = dict(latex="pdf", html="gif") +aafig_format = {"latex": "pdf", "html": "gif"} -aafig_default_options = dict(scale=0.75, aspect=0.5, proportional=True) +aafig_default_options = {"scale": 0.75, "aspect": 0.5, "proportional": True} -def linkcode_resolve(domain, info): # NOQA: C901 +def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object @@ -224,10 +224,7 @@ def linkcode_resolve(domain, info): # NOQA: C901 except Exception: lineno = None - if lineno: - linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) - else: - linespec = "" + linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) if lineno else "" fn = relpath(fn, start=pathlib.Path(tmuxp.__file__).parent) diff --git a/src/tmuxp/cli/debug_info.py b/src/tmuxp/cli/debug_info.py index a23fac1f88..d72e3fc1ac 100644 --- a/src/tmuxp/cli/debug_info.py +++ b/src/tmuxp/cli/debug_info.py @@ -7,7 +7,6 @@ import typing as t from colorama import Fore - from libtmux.__about__ import __version__ as libtmux_version from libtmux.common import get_version, tmux_cmd @@ -34,7 +33,7 @@ def prepend_tab(strings): """ Prepend tab to strings in list. """ - return list(map(lambda x: "\t%s" % x, strings)) + return ["\t%s" % x for x in strings] def output_break(): """ diff --git a/src/tmuxp/cli/freeze.py b/src/tmuxp/cli/freeze.py index 2383a435ba..bd0cf1dac4 100644 --- a/src/tmuxp/cli/freeze.py +++ b/src/tmuxp/cli/freeze.py @@ -5,6 +5,7 @@ import typing as t from libtmux.server import Server + from tmuxp.config_reader import ConfigReader from tmuxp.exc import TmuxpException from tmuxp.workspace.finders import get_workspace_dir diff --git a/src/tmuxp/cli/load.py b/src/tmuxp/cli/load.py index 46862bb423..98722ba96e 100644 --- a/src/tmuxp/cli/load.py +++ b/src/tmuxp/cli/load.py @@ -16,6 +16,7 @@ from libtmux.common import has_gte_version from libtmux.server import Server from libtmux.session import Session + from tmuxp.types import StrPath from .. import config_reader, exc, log, util @@ -91,9 +92,7 @@ def set_layout_hook(session: Session, hook_name: str) -> None: # unset the hook immediately after executing hook_cmd.append( - "set-hook -u -t {target_session} {hook_name}".format( - target_session=session.id, hook_name=hook_name - ) + f"set-hook -u -t {session.id} {hook_name}" ) hook_cmd.append(f"selectw -t {attached_window.id}") @@ -122,8 +121,7 @@ def load_plugins(session_config: t.Dict[str, t.Any]) -> t.List[t.Any]: plugins.append(plugin()) except exc.TmuxpPluginException as error: if not prompt_yes_no( - "%sSkip loading %s?" - % (style(str(error), fg="yellow"), plugin_name), + "{}Skip loading {}?".format(style(str(error), fg="yellow"), plugin_name), default=True, ): tmuxp_echo( diff --git a/src/tmuxp/cli/shell.py b/src/tmuxp/cli/shell.py index 7ea117cbf2..d0774b2dff 100644 --- a/src/tmuxp/cli/shell.py +++ b/src/tmuxp/cli/shell.py @@ -166,7 +166,7 @@ def command_shell( session=session, window_name=args.window_name, current_pane=current_pane ) - pane = util.get_pane(window=window, current_pane=current_pane) # NOQA: F841 + pane = util.get_pane(window=window, current_pane=current_pane) if args.command is not None: exec(args.command) diff --git a/src/tmuxp/cli/utils.py b/src/tmuxp/cli/utils.py index 9a2d41df9c..b38ca68949 100644 --- a/src/tmuxp/cli/utils.py +++ b/src/tmuxp/cli/utils.py @@ -126,7 +126,7 @@ def prompt_choices( if isinstance(choice, str): options.append(choice) elif isinstance(choice, tuple): - options.append("%s [%s]" % (choice, choice[0])) + options.append(f"{choice} [{choice[0]}]") choice = choice[0] _choices.append(choice) diff --git a/src/tmuxp/exc.py b/src/tmuxp/exc.py index e8801e19f0..beb9bbc543 100644 --- a/src/tmuxp/exc.py +++ b/src/tmuxp/exc.py @@ -50,11 +50,11 @@ def __init__( self.cmd = cmd self.output = output self.message = ( - "before_script failed with returncode {returncode}.\n" - "command: {cmd}\n" + f"before_script failed with returncode {self.returncode}.\n" + f"command: {self.cmd}\n" "Error output:\n" - "{output}" - ).format(returncode=self.returncode, cmd=self.cmd, output=self.output) + f"{self.output}" + ) def __str__(self): return self.message diff --git a/src/tmuxp/shell.py b/src/tmuxp/shell.py index 44aa6fe55e..378e8b9755 100644 --- a/src/tmuxp/shell.py +++ b/src/tmuxp/shell.py @@ -32,7 +32,7 @@ def has_ipython() -> bool: def has_ptpython() -> bool: try: - from ptpython.repl import embed, run_config # NOQA F841 + from ptpython.repl import embed, run_config # F841 except ImportError: try: from prompt_toolkit.contrib.repl import embed, run_config # NOQA F841 @@ -44,8 +44,8 @@ def has_ptpython() -> bool: def has_ptipython() -> bool: try: - from ptpython.ipython import embed # NOQA F841 - from ptpython.repl import run_config # NOQA F841 + from ptpython.ipython import embed # F841 + from ptpython.repl import run_config # F841 except ImportError: try: from prompt_toolkit.contrib.ipython import embed # NOQA F841 @@ -80,7 +80,7 @@ def get_bpython(options, extra_args=None): if extra_args is None: extra_args = {} - from bpython import embed # NOQA F841 + from bpython import embed # F841 def launch_bpython(): imported_objects = get_launch_args(**options) diff --git a/src/tmuxp/types.py b/src/tmuxp/types.py index 536225c9f1..f1f6c138f8 100644 --- a/src/tmuxp/types.py +++ b/src/tmuxp/types.py @@ -6,7 +6,7 @@ :class:`StrPath` and :class:`StrOrBytesPath` is based on `typeshed's`_. .. _typeshed's: https://github.com/python/typeshed/blob/9687d5/stdlib/_typeshed/__init__.pyi#L98 -""" # NOQA E501 +""" # E501 from os import PathLike from typing import Union diff --git a/src/tmuxp/util.py b/src/tmuxp/util.py index 90acacf05a..8fc2ddc1cd 100644 --- a/src/tmuxp/util.py +++ b/src/tmuxp/util.py @@ -58,7 +58,7 @@ def run_before_script( if e.errno == 2: raise exc.BeforeLoadScriptNotExists(e, os.path.abspath(script_file)) else: - raise e + raise def oh_my_zsh_auto_title() -> None: @@ -87,7 +87,7 @@ def get_current_pane(server: "Server") -> t.Optional["Pane"]: """Return Pane if one found in env""" if os.getenv("TMUX_PANE") is not None: try: - return [p for p in server.panes if p.pane_id == os.getenv("TMUX_PANE")][0] + return next(p for p in server.panes if p.pane_id == os.getenv("TMUX_PANE")) except IndexError: pass return None @@ -151,9 +151,9 @@ def get_pane(window: "Window", current_pane: t.Optional["Pane"] = None) -> "Pane pane = None try: if current_pane is not None: - pane = window.panes.get(pane_id=current_pane.pane_id) # NOQA: F841 + pane = window.panes.get(pane_id=current_pane.pane_id) else: - pane = window.attached_pane # NOQA: F841 + pane = window.attached_pane except exc.TmuxpException as e: print(e) diff --git a/src/tmuxp/workspace/builder.py b/src/tmuxp/workspace/builder.py index efd2f2fc6a..61b5c937bd 100644 --- a/src/tmuxp/workspace/builder.py +++ b/src/tmuxp/workspace/builder.py @@ -141,7 +141,7 @@ def __init__( self, session_config: t.Dict[str, t.Any], server: Server, - plugins: t.List[t.Any] = [], + plugins: t.Optional[t.List[t.Any]] = None, ) -> None: """Initialize workspace loading. @@ -162,6 +162,8 @@ def __init__( ``self.session``. """ + if plugins is None: + plugins = [] if not session_config: raise exc.EmptyWorkspaceException("Session configuration is empty.") @@ -276,9 +278,9 @@ def build(self, session: t.Optional[Session] = None, append: bool = False) -> No if "start_directory" in self.session_config: cwd = self.session_config["start_directory"] run_before_script(self.session_config["before_script"], cwd=cwd) - except Exception as e: + except Exception: self.session.kill_session() - raise e + raise if "options" in self.session_config: for option, value in self.session_config["options"].items(): @@ -349,10 +351,7 @@ def iter_create_windows( for window_iterator, window_config in enumerate( self.session_config["windows"], start=1 ): - if "window_name" not in window_config: - window_name = None - else: - window_name = window_config["window_name"] + window_name = window_config.get("window_name", None) is_first_window_pass = self.first_window_pass( window_iterator, session, append @@ -363,20 +362,14 @@ def iter_create_windows( w1 = session.attached_window w1.move_window("99") - if "start_directory" in window_config: - start_directory = window_config["start_directory"] - else: - start_directory = None + start_directory = window_config.get("start_directory", None) # If the first pane specifies a start_directory, use that instead. panes = window_config["panes"] if panes and "start_directory" in panes[0]: start_directory = panes[0]["start_directory"] - if "window_shell" in window_config: - window_shell = window_config["window_shell"] - else: - window_shell = None + window_shell = window_config.get("window_shell", None) # If the first pane specifies a shell, use that instead. try: diff --git a/src/tmuxp/workspace/finders.py b/src/tmuxp/workspace/finders.py index 2cb0360af9..b73d84f410 100644 --- a/src/tmuxp/workspace/finders.py +++ b/src/tmuxp/workspace/finders.py @@ -19,11 +19,7 @@ def is_workspace_file( filename: str, - extensions: t.Union["ValidExtensions", t.List["ValidExtensions"]] = [ - ".yml", - ".yaml", - ".json", - ], + extensions: t.Union["ValidExtensions", t.List["ValidExtensions"]] = None, ) -> bool: """ Return True if file has a valid workspace file type. @@ -39,13 +35,15 @@ def is_workspace_file( ------- bool """ + if extensions is None: + extensions = [".yml", ".yaml", ".json"] extensions = [extensions] if isinstance(extensions, str) else extensions return any(filename.endswith(e) for e in extensions) def in_dir( workspace_dir: t.Union[pathlib.Path, str] = os.path.expanduser("~/.tmuxp"), - extensions: t.List["ValidExtensions"] = [".yml", ".yaml", ".json"], + extensions: t.Optional[t.List["ValidExtensions"]] = None, ) -> t.List[str]: """ @@ -62,6 +60,8 @@ def in_dir( ------- list """ + if extensions is None: + extensions = [".yml", ".yaml", ".json"] workspace_files = [] for filename in os.listdir(workspace_dir): diff --git a/src/tmuxp/workspace/freezer.py b/src/tmuxp/workspace/freezer.py index b9b4ab9ddb..ab29b36caa 100644 --- a/src/tmuxp/workspace/freezer.py +++ b/src/tmuxp/workspace/freezer.py @@ -1,6 +1,7 @@ +import typing as t + from libtmux.pane import Pane from libtmux.session import Session -import typing as t def inline(workspace_dict): @@ -23,7 +24,7 @@ def inline(workspace_dict): ): workspace_dict["shell_command"] = workspace_dict["shell_command"][0] - if len(workspace_dict.keys()) == int(1): + if len(workspace_dict.keys()) == 1: workspace_dict = workspace_dict["shell_command"] if ( "shell_command_before" in workspace_dict diff --git a/src/tmuxp/workspace/importers.py b/src/tmuxp/workspace/importers.py index b5eff6606b..9f60208f28 100644 --- a/src/tmuxp/workspace/importers.py +++ b/src/tmuxp/workspace/importers.py @@ -126,10 +126,7 @@ def import_teamocil(workspace_dict: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: if "session" in workspace_dict: workspace_dict = workspace_dict["session"] - if "name" in workspace_dict: - tmuxp_workspace["session_name"] = workspace_dict["name"] - else: - tmuxp_workspace["session_name"] = None + tmuxp_workspace["session_name"] = workspace_dict.get("name", None) if "root" in workspace_dict: tmuxp_workspace["start_directory"] = workspace_dict.pop("root") @@ -144,10 +141,10 @@ def import_teamocil(workspace_dict: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]: if "filters" in w: if "before" in w["filters"]: - for b in w["filters"]["before"]: + for _b in w["filters"]["before"]: window_dict["shell_command_before"] = w["filters"]["before"] if "after" in w["filters"]: - for b in w["filters"]["after"]: + for _b in w["filters"]["after"]: window_dict["shell_command_after"] = w["filters"]["after"] if "root" in w: diff --git a/src/tmuxp/workspace/loader.py b/src/tmuxp/workspace/loader.py index 1f23ecee18..700a504097 100644 --- a/src/tmuxp/workspace/loader.py +++ b/src/tmuxp/workspace/loader.py @@ -48,7 +48,7 @@ def expand_cmd(p: Dict) -> Dict: if not cmds or any(a == cmds for a in [None, "blank", "pane"]): cmds = [] - if isinstance(cmds, list) and len(cmds) == int(1): + if isinstance(cmds, list) and len(cmds) == 1: if any(a in cmds for a in [None, "blank", "pane"]): cmds = [] @@ -206,15 +206,9 @@ def trickle(workspace_dict): # prepends a pane's ``shell_command`` list with the window and sessions' # ``shell_command_before``. - if "start_directory" in workspace_dict: - session_start_directory = workspace_dict["start_directory"] - else: - session_start_directory = None + session_start_directory = workspace_dict.get("start_directory", None) - if "suppress_history" in workspace_dict: - suppress_history = workspace_dict["suppress_history"] - else: - suppress_history = None + suppress_history = workspace_dict.get("suppress_history", None) for window_dict in workspace_dict["windows"]: @@ -232,9 +226,8 @@ def trickle(workspace_dict): window_dict["start_directory"] = window_start_path # We only need to trickle to the window, workspace builder checks wconf - if suppress_history is not None: - if "suppress_history" not in window_dict: - window_dict["suppress_history"] = suppress_history + if suppress_history is not None and "suppress_history" not in window_dict: + window_dict["suppress_history"] = suppress_history # If panes were NOT specified for a window, assume that a single pane # with no shell commands is desired diff --git a/src/tmuxp/workspace/validation.py b/src/tmuxp/workspace/validation.py index bbe1ede7f9..507ce64c7e 100644 --- a/src/tmuxp/workspace/validation.py +++ b/src/tmuxp/workspace/validation.py @@ -27,8 +27,7 @@ def validate_schema(workspace_dict: t.Any) -> bool: if "window_name" not in window: raise exc.WorkspaceError('workspace window is missing "window_name"') - if "plugins" in workspace_dict: - if not isinstance(workspace_dict["plugins"], list): - raise exc.WorkspaceError('"plugins" only supports list type') + if "plugins" in workspace_dict and not isinstance(workspace_dict["plugins"], list): + raise exc.WorkspaceError('"plugins" only supports list type') return True diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 1358491f29..7a91dc90ac 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -1,12 +1,13 @@ import argparse +import contextlib import os import pathlib import typing as t -import pytest - import libtmux +import pytest from libtmux.server import Server + from tmuxp import cli from tmuxp.cli.import_config import get_teamocil_dir, get_tmuxinator_dir from tmuxp.cli.load import _reattach, load_plugins @@ -42,10 +43,9 @@ def test_help( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture, ) -> None: - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + result = capsys.readouterr() assert "usage: tmuxp [-h] [--version] [--log-level log-level]" in result.out @@ -57,7 +57,7 @@ def test_resolve_behavior( expect = tmp_path monkeypatch.chdir(tmp_path) assert pathlib.Path("../").resolve() == pathlib.Path(os.path.dirname(expect)) - assert pathlib.Path(".").resolve() == expect + assert pathlib.Path().resolve() == expect assert pathlib.Path("./").resolve() == expect assert pathlib.Path(expect).resolve() == expect @@ -130,10 +130,9 @@ def test_reattach_plugins( ) builder.build() - try: + with contextlib.suppress(libtmux.exc.LibTmuxException): _reattach(builder) - except libtmux.exc.LibTmuxException: - pass + assert builder.session is not None proc = builder.session.cmd("display-message", "-p", "'#S'") diff --git a/tests/cli/test_convert.py b/tests/cli/test_convert.py index b923c4ea1d..66805476e5 100644 --- a/tests/cli/test_convert.py +++ b/tests/cli/test_convert.py @@ -1,3 +1,4 @@ +import contextlib import io import json import pathlib @@ -41,10 +42,9 @@ def test_convert( input_args = "y\ny\n" if "-y" not in cli_args else "" monkeypatch.setattr("sys.stdin", io.StringIO(input_args)) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + tmuxp_json = tmp_path / ".tmuxp.json" assert tmuxp_json.exists() assert tmuxp_json.open().read() == json.dumps({"session_name": "hello"}, indent=2) @@ -76,10 +76,9 @@ def test_convert_json( input_args = "y\ny\n" if "-y" not in cli_args else "" monkeypatch.setattr("sys.stdin", io.StringIO(input_args)) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + tmuxp_yaml = tmp_path / ".tmuxp.yaml" assert tmuxp_yaml.exists() diff --git a/tests/cli/test_freeze.py b/tests/cli/test_freeze.py index 87ddc58c14..cbe06aa1ab 100644 --- a/tests/cli/test_freeze.py +++ b/tests/cli/test_freeze.py @@ -1,10 +1,11 @@ +import contextlib import io import pathlib import typing as t import pytest - from libtmux.server import Server + from tmuxp import cli from tmuxp.config_reader import ConfigReader @@ -47,13 +48,12 @@ def test_freeze( monkeypatch.chdir(tmp_path) # Use tmux server (socket name) used in the test assert server.socket_name is not None - cli_args = cli_args + ["-L", server.socket_name] + cli_args = [*cli_args, "-L", server.socket_name] monkeypatch.setattr("sys.stdin", io.StringIO("".join(inputs))) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + yaml_config_path = tmp_path / "la.yaml" assert yaml_config_path.exists() @@ -93,13 +93,12 @@ def test_freeze_overwrite( monkeypatch.chdir(tmp_path) # Use tmux server (socket name) used in the test assert server.socket_name is not None - cli_args = cli_args + ["-L", server.socket_name] + cli_args = [*cli_args, "-L", server.socket_name] monkeypatch.setattr("sys.stdin", io.StringIO("".join(inputs))) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + yaml_config_path = tmp_path / "exists.yaml" assert yaml_config_path.exists() diff --git a/tests/cli/test_import.py b/tests/cli/test_import.py index 0d1e76a922..59faba784e 100644 --- a/tests/cli/test_import.py +++ b/tests/cli/test_import.py @@ -1,3 +1,4 @@ +import contextlib import io import pathlib import typing as t @@ -61,10 +62,9 @@ def test_import_teamocil( monkeypatch.chdir(tmp_path) monkeypatch.setattr("sys.stdin", io.StringIO("".join(inputs))) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + new_config_yaml = tmp_path / "la.yaml" assert new_config_yaml.exists() @@ -109,10 +109,9 @@ def test_import_tmuxinator( monkeypatch.chdir(tmp_path) monkeypatch.setattr("sys.stdin", io.StringIO("".join(inputs))) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + new_config_yaml = tmp_path / "la.yaml" assert new_config_yaml.exists() diff --git a/tests/cli/test_load.py b/tests/cli/test_load.py index 6a42ce1ef7..a4a28318e5 100644 --- a/tests/cli/test_load.py +++ b/tests/cli/test_load.py @@ -1,15 +1,15 @@ +import contextlib import io import pathlib import typing as t -import pytest - -from pytest_mock import MockerFixture - import libtmux +import pytest from libtmux.common import has_lt_version from libtmux.server import Server from libtmux.session import Session +from pytest_mock import MockerFixture + from tmuxp import cli from tmuxp.cli.load import ( _load_append_windows_to_current_session, @@ -282,22 +282,19 @@ def test_load( config_path.format(tmp_path=tmp_path, TMUXP_CONFIGDIR=tmuxp_configdir) ) tmuxp_config.write_text( - """ + f""" session_name: {session_name} windows: - window_name: test panes: - - """.format( - session_name=session_name - ), + """, encoding="utf-8", ) - try: + with contextlib.suppress(SystemExit): cli.cli([*cli_args, "-d", "-L", server.socket_name, "-y"]) - except SystemExit: - pass + result = capsys.readouterr() output = "".join(list(result.out)) @@ -363,7 +360,7 @@ def test_load_zsh_autotitle_warning( # Use tmux server (socket name) used in the test assert server.socket_name is not None - cli_args = cli_args + ["-L", server.socket_name] + cli_args = [*cli_args, "-L", server.socket_name] cli.cli(cli_args) result = capsys.readouterr() @@ -413,10 +410,9 @@ def test_load_log_file( monkeypatch.chdir(tmp_path) - try: + with contextlib.suppress(Exception): cli.cli(cli_args) - except Exception: - pass + result = capsys.readouterr() log_file_path = tmp_path / "log.txt" assert "Loading" in log_file_path.open().read() @@ -457,10 +453,9 @@ def test_load_plugins(monkeypatch_plugin_test_packages: None) -> None: def test_load_plugins_version_fail_skip( monkeypatch_plugin_test_packages, cli_args, inputs, capsys: pytest.CaptureFixture ) -> None: - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + result = capsys.readouterr() assert "[Loading]" in result.out @@ -484,10 +479,9 @@ def test_load_plugins_version_fail_no_skip( ) -> None: monkeypatch.setattr("sys.stdin", io.StringIO("".join(inputs))) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + result = capsys.readouterr() assert "[Not Skipping]" in result.out @@ -502,10 +496,9 @@ def test_load_plugins_plugin_missing( cli_args: t.List[str], capsys: pytest.CaptureFixture, ) -> None: - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + result = capsys.readouterr() assert "[Plugin Error]" in result.out diff --git a/tests/cli/test_ls.py b/tests/cli/test_ls.py index 75d6de7db5..fa3c08d0d0 100644 --- a/tests/cli/test_ls.py +++ b/tests/cli/test_ls.py @@ -1,3 +1,4 @@ +import contextlib import os import pathlib @@ -36,10 +37,9 @@ def test_ls_cli( else: location.touch() - try: + with contextlib.suppress(SystemExit): cli.cli(["ls"]) - except SystemExit: - pass + cli_output = capsys.readouterr().out assert cli_output == "\n".join(stems) + "\n" diff --git a/tests/cli/test_shell.py b/tests/cli/test_shell.py index 2824120592..7b5861e708 100644 --- a/tests/cli/test_shell.py +++ b/tests/cli/test_shell.py @@ -1,12 +1,13 @@ +import contextlib import io import pathlib import subprocess import typing as t import pytest - from libtmux.server import Server from libtmux.session import Session + from tmuxp import cli, exc @@ -98,13 +99,13 @@ def test_shell( assert window.attached_pane is not None - template_ctx = dict( - SOCKET_NAME=server.socket_name, - SESSION_NAME=session.name, - WINDOW_NAME=window_name, - PANE_ID=window.attached_pane.id, - SERVER_SOCKET_NAME=server.socket_name, - ) + template_ctx = { + "SOCKET_NAME": server.socket_name, + "SESSION_NAME": session.name, + "WINDOW_NAME": window_name, + "PANE_ID": window.attached_pane.id, + "SERVER_SOCKET_NAME": server.socket_name, + } cli_args = cli_cmd + [cli_arg.format(**template_ctx) for cli_arg in cli_args] @@ -191,11 +192,11 @@ def test_shell_target_missing( assert session.name is not None template_ctx.update( - dict( - SOCKET_NAME=server.socket_name, - SESSION_NAME=session.name, - WINDOW_NAME=template_ctx.get("window_name", window_name), - ) + { + "SOCKET_NAME": server.socket_name, + "SESSION_NAME": session.name, + "WINDOW_NAME": template_ctx.get("window_name", window_name), + } ) cli_args = cli_cmd + [cli_arg.format(**template_ctx) for cli_arg in cli_args] @@ -265,13 +266,13 @@ def test_shell_interactive( assert window.attached_pane is not None - template_ctx = dict( - SOCKET_NAME=server.socket_name, - SESSION_NAME=session.name, - WINDOW_NAME=window_name, - PANE_ID=window.attached_pane.id, - SERVER_SOCKET_NAME=server.socket_name, - ) + template_ctx = { + "SOCKET_NAME": server.socket_name, + "SESSION_NAME": session.name, + "WINDOW_NAME": window_name, + "PANE_ID": window.attached_pane.id, + "SERVER_SOCKET_NAME": server.socket_name, + } cli_args = cli_cmd + [cli_arg.format(**template_ctx) for cli_arg in cli_args] @@ -280,9 +281,8 @@ def test_shell_interactive( monkeypatch.chdir(tmp_path) monkeypatch.setattr("sys.stdin", io.StringIO("exit()\r")) - try: + with contextlib.suppress(SystemExit): cli.cli(cli_args) - except SystemExit: - pass + result = capsys.readouterr() assert message.format(**template_ctx) in result.err diff --git a/tests/fixtures/__init__.py b/tests/fixtures/__init__.py index a81b5f2914..eb018c3ff0 100644 --- a/tests/fixtures/__init__.py +++ b/tests/fixtures/__init__.py @@ -1 +1 @@ -from . import utils # noqa +from . import utils diff --git a/tests/fixtures/import_teamocil/__init__.py b/tests/fixtures/import_teamocil/__init__.py index 7fe671395a..6d5ce91af9 100644 --- a/tests/fixtures/import_teamocil/__init__.py +++ b/tests/fixtures/import_teamocil/__init__.py @@ -1 +1 @@ -from . import layouts, test1, test2, test3, test4 # noqa +from . import layouts, test1, test2, test3, test4 diff --git a/tests/fixtures/import_tmuxinator/__init__.py b/tests/fixtures/import_tmuxinator/__init__.py index bbdbf699ad..91bc1d0f43 100644 --- a/tests/fixtures/import_tmuxinator/__init__.py +++ b/tests/fixtures/import_tmuxinator/__init__.py @@ -1 +1 @@ -from . import test1, test2, test3 # noqa +from . import test1, test2, test3 diff --git a/tests/fixtures/workspace/__init__.py b/tests/fixtures/workspace/__init__.py index 1169223091..097409c156 100644 --- a/tests/fixtures/workspace/__init__.py +++ b/tests/fixtures/workspace/__init__.py @@ -1,4 +1,4 @@ -from . import ( # noqa +from . import ( expand1, expand2, expand_blank, diff --git a/tests/tests/test_helpers.py b/tests/tests/test_helpers.py index 5e93ea45eb..ce601ad25a 100644 --- a/tests/tests/test_helpers.py +++ b/tests/tests/test_helpers.py @@ -1,6 +1,5 @@ """Tests for .'s helper and utility functions.""" import pytest - from libtmux.server import Server from libtmux.test import get_test_session_name, temp_session diff --git a/tests/workspace/test_builder.py b/tests/workspace/test_builder.py index 30d0e85ade..bb8a0f3c80 100644 --- a/tests/workspace/test_builder.py +++ b/tests/workspace/test_builder.py @@ -5,14 +5,14 @@ import time import typing as t -import pytest - import libtmux +import pytest from libtmux.common import has_gte_version, has_lt_version from libtmux.pane import Pane from libtmux.session import Session from libtmux.test import retry_until, temp_session from libtmux.window import Window + from tmuxp import exc from tmuxp.cli.load import load_plugins from tmuxp.config_reader import ConfigReader @@ -87,10 +87,7 @@ def test_focus_pane_index(session): assert isinstance(_pane_base_index, int) pane_base_index = int(_pane_base_index) - if not pane_base_index: - pane_base_index = 0 - else: - pane_base_index = int(pane_base_index) + pane_base_index = 0 if not pane_base_index else int(pane_base_index) # get the pane index for each pane pane_base_indexes = [] @@ -231,7 +228,7 @@ def test_global_options(session): _status_position = session.show_option("status-position", _global=True) assert isinstance(_status_position, str) assert "top" in _status_position - assert 493 == session.show_option("repeat-time", _global=True) + assert session.show_option("repeat-time", _global=True) == 493 def test_global_session_env_options(session, monkeypatch): @@ -603,7 +600,7 @@ def test_start_directory_sets_session_path(server): builder.build() session = builder.session - expected = "{0}|/usr".format(session.id) + expected = f"{session.id}|/usr" cmd = server.cmd("list-sessions", "-F", "#{session_id}|#{session_path}") assert expected in cmd.stdout diff --git a/tests/workspace/test_config.py b/tests/workspace/test_config.py index 9fe380eba6..bf6da546e4 100644 --- a/tests/workspace/test_config.py +++ b/tests/workspace/test_config.py @@ -49,7 +49,7 @@ def test_find_workspace_file(tmp_path: pathlib.Path): garbage_file = tmp_path / "config.psd" garbage_file.write_text("wat", encoding="utf-8") - for r, d, f in os.walk(str(tmp_path)): + for _r, _d, f in os.walk(str(tmp_path)): for filela in (x for x in f if x.endswith((".json", ".ini", "yaml"))): configs.append(str(tmp_path / filela))