diff --git a/docs/conf.py b/docs/conf.py index 9dcafd9c0..7556a4c37 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -22,108 +22,108 @@ extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx_autodoc_typehints', - 'sphinx.ext.todo', - 'sphinx.ext.linkcode', - 'sphinx.ext.napoleon', - 'alagitpull', - 'sphinx_issues', - 'myst_parser', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx_autodoc_typehints", + "sphinx.ext.todo", + "sphinx.ext.linkcode", + "sphinx.ext.napoleon", + "alagitpull", + "sphinx_issues", + "myst_parser", ] myst_enable_extensions = ["colon_fence"] -issues_github_path = about['__github__'].replace('https://github.com/', '') +issues_github_path = about["__github__"].replace("https://github.com/", "") -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = {'.rst': 'restructuredtext', '.md': 'markdown'} +source_suffix = {".rst": "restructuredtext", ".md": "markdown"} -master_doc = 'index' +master_doc = "index" -project = about['__title__'] -copyright = about['__copyright__'] +project = about["__title__"] +copyright = about["__copyright__"] -version = '%s' % ('.'.join(about['__version__'].split('.'))[:2]) -release = '%s' % (about['__version__']) +version = "%s" % (".".join(about["__version__"].split("."))[:2]) +release = "%s" % (about["__version__"]) -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] -pygments_style = 'sphinx' +pygments_style = "sphinx" html_theme_path = [alagitpull.get_path()] -html_favicon = '_static/favicon.ico' -html_theme = 'alagitpull' +html_favicon = "_static/favicon.ico" +html_theme = "alagitpull" html_theme_options = { - 'logo': 'img/libtmux.svg', - 'github_user': 'tmux-python', - 'github_repo': 'libtmux', - 'github_type': 'star', - 'github_banner': True, - 'projects': alagitpull.projects, - 'project_name': about['__title__'], - 'project_title': about['__title__'], - 'project_description': about['__description__'], - 'project_url': about['__docs__'], - 'show_meta_manifest_tag': True, - 'show_meta_og_tags': True, - 'show_meta_app_icon_tags': True, + "logo": "img/libtmux.svg", + "github_user": "tmux-python", + "github_repo": "libtmux", + "github_type": "star", + "github_banner": True, + "projects": alagitpull.projects, + "project_name": about["__title__"], + "project_title": about["__title__"], + "project_description": about["__description__"], + "project_url": about["__docs__"], + "show_meta_manifest_tag": True, + "show_meta_og_tags": True, + "show_meta_app_icon_tags": True, } -alagitpull_internal_hosts = ['libtmux.git-pull.com', '0.0.0.0'] +alagitpull_internal_hosts = ["libtmux.git-pull.com", "0.0.0.0"] alagitpull_external_hosts_new_window = True html_sidebars = { - '**': [ - 'about.html', - 'navigation.html', - 'relations.html', - 'more.html', - 'book.html', - 'searchbox.html', + "**": [ + "about.html", + "navigation.html", + "relations.html", + "more.html", + "book.html", + "searchbox.html", ] } -html_theme_path = ['_themes'] -html_static_path = ['_static'] -html_extra_path = ['manifest.json'] +html_theme_path = ["_themes"] +html_static_path = ["_static"] +html_extra_path = ["manifest.json"] -htmlhelp_basename = '%sdoc' % about['__title__'] +htmlhelp_basename = "%sdoc" % about["__title__"] latex_documents = [ ( - 'index', - '{}.tex'.format(about['__package_name__']), - '{} Documentation'.format(about['__title__']), - about['__author__'], - 'manual', + "index", + "{}.tex".format(about["__package_name__"]), + "{} Documentation".format(about["__title__"]), + about["__author__"], + "manual", ) ] man_pages = [ ( - 'index', - about['__package_name__'], - '{} Documentation'.format(about['__title__']), - about['__author__'], + "index", + about["__package_name__"], + "{} Documentation".format(about["__title__"]), + about["__author__"], 1, ) ] texinfo_documents = [ ( - 'index', - '{}'.format(about['__package_name__']), - '{} Documentation'.format(about['__title__']), - about['__author__'], - about['__package_name__'], - about['__description__'], - 'Miscellaneous', + "index", + "{}".format(about["__package_name__"]), + "{} Documentation".format(about["__title__"]), + about["__author__"], + about["__package_name__"], + about["__description__"], + "Miscellaneous", ) ] -intersphinx_mapping = {'http://docs.python.org/': None} +intersphinx_mapping = {"http://docs.python.org/": None} def linkcode_resolve(domain, info): # NOQA: C901 @@ -135,18 +135,18 @@ def linkcode_resolve(domain, info): # NOQA: C901 From https://github.com/numpy/numpy/blob/v1.15.1/doc/source/conf.py, 7c49cfa on Jul 31. License BSD-3. https://github.com/numpy/numpy/blob/v1.15.1/LICENSE.txt """ - if domain != 'py': + if domain != "py": return None - modname = info['module'] - fullname = info['fullname'] + modname = info["module"] + fullname = info["fullname"] submod = sys.modules.get(modname) if submod is None: return None obj = submod - for part in fullname.split('.'): + for part in fullname.split("."): try: obj = getattr(obj, part) except Exception: @@ -180,18 +180,18 @@ def linkcode_resolve(domain, info): # NOQA: C901 fn = relpath(fn, start=dirname(libtmux.__file__)) - if 'dev' in about['__version__']: + if "dev" in about["__version__"]: return "%s/blob/master/%s/%s%s" % ( - about['__github__'], - about['__package_name__'], + about["__github__"], + about["__package_name__"], fn, linespec, ) else: return "%s/blob/v%s/%s/%s%s" % ( - about['__github__'], - about['__version__'], - about['__package_name__'], + about["__github__"], + about["__version__"], + about["__package_name__"], fn, linespec, ) diff --git a/libtmux/__about__.py b/libtmux/__about__.py index f8070c438..62b41c7e9 100644 --- a/libtmux/__about__.py +++ b/libtmux/__about__.py @@ -1,12 +1,12 @@ -__title__ = 'libtmux' -__package_name__ = 'libtmux' -__version__ = '0.11.0b0' -__description__ = 'scripting library / orm for tmux' -__email__ = 'tony@git-pull.com' -__author__ = 'Tony Narlock' -__github__ = 'https://github.com/tmux-python/libtmux' -__docs__ = 'https://libtmux.git-pull.com' -__tracker__ = 'https://github.com/tmux-python/libtmux/issues' -__pypi__ = 'https://pypi.org/project/libtmux/' -__license__ = 'MIT' -__copyright__ = 'Copyright 2016- Tony Narlock' +__title__ = "libtmux" +__package_name__ = "libtmux" +__version__ = "0.11.0b0" +__description__ = "scripting library / orm for tmux" +__email__ = "tony@git-pull.com" +__author__ = "Tony Narlock" +__github__ = "https://github.com/tmux-python/libtmux" +__docs__ = "https://libtmux.git-pull.com" +__tracker__ = "https://github.com/tmux-python/libtmux/issues" +__pypi__ = "https://pypi.org/project/libtmux/" +__license__ = "MIT" +__copyright__ = "Copyright 2016- Tony Narlock" diff --git a/libtmux/_compat.py b/libtmux/_compat.py index 2739bb0a8..e735bed9d 100644 --- a/libtmux/_compat.py +++ b/libtmux/_compat.py @@ -9,9 +9,9 @@ def console_to_str(s): """From pypa/pip project, pip.backwardwardcompat. License MIT.""" try: - return s.decode(console_encoding, 'ignore') + return s.decode(console_encoding, "ignore") except UnicodeDecodeError: - return s.decode('utf_8', 'ignore') + return s.decode("utf_8", "ignore") def reraise(tp, value, tb=None): @@ -24,4 +24,4 @@ def str_from_console(s): try: return str(s) except UnicodeDecodeError: - return str(s, encoding='utf_8') + return str(s, encoding="utf_8") diff --git a/libtmux/common.py b/libtmux/common.py index 299388b74..f0dd9c2f6 100644 --- a/libtmux/common.py +++ b/libtmux/common.py @@ -20,10 +20,10 @@ #: Minimum version of tmux required to run libtmux -TMUX_MIN_VERSION = '1.8' +TMUX_MIN_VERSION = "1.8" #: Most recent version of tmux supported -TMUX_MAX_VERSION = '2.4' +TMUX_MAX_VERSION = "2.4" class EnvironmentMixin(object): @@ -49,7 +49,7 @@ def set_environment(self, name, value): option : str environment value. """ - args = ['set-environment'] + args = ["set-environment"] if self._add_option: args += [self._add_option] @@ -60,7 +60,7 @@ def set_environment(self, name, value): if proc.stderr: if isinstance(proc.stderr, list) and len(proc.stderr) == int(1): proc.stderr = proc.stderr[0] - raise ValueError('tmux set-environment stderr: %s' % proc.stderr) + raise ValueError("tmux set-environment stderr: %s" % proc.stderr) def unset_environment(self, name): """ @@ -71,17 +71,17 @@ def unset_environment(self, name): name : str the environment variable name. such as 'PATH'. """ - args = ['set-environment'] + args = ["set-environment"] if self._add_option: args += [self._add_option] - args += ['-u', name] + args += ["-u", name] proc = self.cmd(*args) if proc.stderr: if isinstance(proc.stderr, list) and len(proc.stderr) == int(1): proc.stderr = proc.stderr[0] - raise ValueError('tmux set-environment stderr: %s' % proc.stderr) + raise ValueError("tmux set-environment stderr: %s" % proc.stderr) def remove_environment(self, name): """Remove environment variable ``$ tmux set-environment -r ``. @@ -91,17 +91,17 @@ def remove_environment(self, name): name : str the environment variable name. such as 'PATH'. """ - args = ['set-environment'] + args = ["set-environment"] if self._add_option: args += [self._add_option] - args += ['-r', name] + args += ["-r", name] proc = self.cmd(*args) if proc.stderr: if isinstance(proc.stderr, list) and len(proc.stderr) == int(1): proc.stderr = proc.stderr[0] - raise ValueError('tmux set-environment stderr: %s' % proc.stderr) + raise ValueError("tmux set-environment stderr: %s" % proc.stderr) def show_environment(self, name=None): """Show environment ``$ tmux show-environment -t [session] ``. @@ -120,13 +120,13 @@ def show_environment(self, name=None): environmental variables in dict, if no name, or str if name entered. """ - tmux_args = ['show-environment'] + tmux_args = ["show-environment"] if self._add_option: tmux_args += [self._add_option] if name: tmux_args += [name] vars = self.cmd(*tmux_args).stdout - vars = [tuple(item.split('=', 1)) for item in vars] + vars = [tuple(item.split("=", 1)) for item in vars] vars_dict = {} for t in vars: if len(t) == 2: @@ -134,7 +134,7 @@ def show_environment(self, name=None): elif len(t) == 1: vars_dict[t[0]] = True else: - raise ValueError('unexpected variable %s', t) + raise ValueError("unexpected variable %s", t) if name: return vars_dict.get(name) @@ -184,12 +184,12 @@ class tmux_cmd(object): def __init__(self, *args, **kwargs): tmux_bin = which( - 'tmux', + "tmux", default_paths=kwargs.get( - 'tmux_search_paths', - ['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin'], + "tmux_search_paths", + ["/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/local/bin"], ), - append_env_path=kwargs.get('append_env_path', True), + append_env_path=kwargs.get("append_env_path", True), ) if not tmux_bin: raise (exc.TmuxCommandNotFound) @@ -207,23 +207,23 @@ def __init__(self, *args, **kwargs): stdout, stderr = self.process.communicate() returncode = self.process.returncode except Exception as e: - logger.error('Exception for %s: \n%s' % (subprocess.list2cmdline(cmd), e)) + logger.error("Exception for %s: \n%s" % (subprocess.list2cmdline(cmd), e)) self.returncode = returncode self.stdout = console_to_str(stdout) - self.stdout = self.stdout.split('\n') + self.stdout = self.stdout.split("\n") self.stdout = list(filter(None, self.stdout)) # filter empty values self.stderr = console_to_str(stderr) - self.stderr = self.stderr.split('\n') + self.stderr = self.stderr.split("\n") self.stderr = list(filter(None, self.stderr)) # filter empty values - if 'has-session' in cmd and len(self.stderr): + if "has-session" in cmd and len(self.stderr): if not self.stdout: self.stdout = self.stderr[0] - logger.debug('self.stdout for %s: \n%s' % (' '.join(cmd), self.stdout)) + logger.debug("self.stdout for %s: \n%s" % (" ".join(cmd), self.stdout)) class TmuxMappingObject(MutableMapping): @@ -272,7 +272,7 @@ def __getattr__(self, key): try: return self._info[self.formatter_prefix + key] except KeyError: - raise AttributeError('%s has no property %s' % (self.__class__, key)) + raise AttributeError("%s has no property %s" % (self.__class__, key)) class TmuxRelationalObject(object): @@ -376,7 +376,7 @@ def get_by_id(self, id): def which( exe=None, - default_paths=['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin'], + default_paths=["/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/local/bin"], append_env_path=True, ): """ @@ -415,7 +415,7 @@ def _is_executable_file_or_link(exe): # win' for cases to find optional alternatives if append_env_path: search_path = ( - os.environ.get('PATH') and os.environ['PATH'].split(os.pathsep) or list() + os.environ.get("PATH") and os.environ["PATH"].split(os.pathsep) or list() ) else: search_path = [] @@ -428,8 +428,8 @@ def _is_executable_file_or_link(exe): if _is_executable_file_or_link(full_path): return full_path logger.info( - '\'{0}\' could not be found in the following search path: ' - '\'{1}\''.format(exe, search_path) + "'{0}' could not be found in the following search path: " + "'{1}'".format(exe, search_path) ) return None @@ -450,24 +450,24 @@ def get_version(): :class:`distutils.version.LooseVersion` tmux version according to :func:`libtmux.common.which`'s tmux """ - proc = tmux_cmd('-V') + proc = tmux_cmd("-V") if proc.stderr: - if proc.stderr[0] == 'tmux: unknown option -- V': + if proc.stderr[0] == "tmux: unknown option -- V": if sys.platform.startswith("openbsd"): # openbsd has no tmux -V - return LooseVersion('%s-openbsd' % TMUX_MAX_VERSION) + return LooseVersion("%s-openbsd" % TMUX_MAX_VERSION) raise exc.LibTmuxException( - 'libtmux supports tmux %s and greater. This system' - ' is running tmux 1.3 or earlier.' % TMUX_MIN_VERSION + "libtmux supports tmux %s and greater. This system" + " is running tmux 1.3 or earlier." % TMUX_MIN_VERSION ) raise exc.VersionTooLow(proc.stderr) - version = proc.stdout[0].split('tmux ')[1] + version = proc.stdout[0].split("tmux ")[1] # Allow latest tmux HEAD - if version == 'master': - return LooseVersion('%s-master' % TMUX_MAX_VERSION) + if version == "master": + return LooseVersion("%s-master" % TMUX_MAX_VERSION) - version = re.sub(r'[a-z-]', '', version) + version = re.sub(r"[a-z-]", "", version) return LooseVersion(version) @@ -590,8 +590,8 @@ def has_minimum_version(raises=True): if get_version() < LooseVersion(TMUX_MIN_VERSION): if raises: raise exc.VersionTooLow( - 'libtmux only supports tmux %s and greater. This system' - ' has %s installed. Upgrade your tmux to use libtmux.' + "libtmux only supports tmux %s and greater. This system" + " has %s installed. Upgrade your tmux to use libtmux." % (TMUX_MIN_VERSION, get_version()) ) else: @@ -618,13 +618,13 @@ def session_check_name(session_name): """ if not session_name or len(session_name) == 0: raise exc.BadSessionName("tmux session names may not be empty.") - elif '.' in session_name: + elif "." in session_name: raise exc.BadSessionName( - "tmux session name \"%s\" may not contain periods.", session_name + 'tmux session name "%s" may not contain periods.', session_name ) - elif ':' in session_name: + elif ":" in session_name: raise exc.BadSessionName( - "tmux session name \"%s\" may not contain colons.", session_name + 'tmux session name "%s" may not contain colons.', session_name ) @@ -655,11 +655,11 @@ def handle_option_error(error): :exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption` """ - if 'unknown option' in error: + if "unknown option" in error: raise exc.UnknownOption(error) - elif 'invalid option' in error: + elif "invalid option" in error: raise exc.InvalidOption(error) - elif 'ambiguous option' in error: + elif "ambiguous option" in error: raise exc.AmbiguousOption(error) else: raise exc.OptionError(error) # Raise generic option error diff --git a/libtmux/formats.py b/libtmux/formats.py index e48f4409a..ce3745318 100644 --- a/libtmux/formats.py +++ b/libtmux/formats.py @@ -11,87 +11,87 @@ FORMAT_SEPARATOR = os.environ.get("LIBTMUX_TMUX_FORMAT_SEPARATOR", "|") SESSION_FORMATS = [ - 'session_name', - 'session_windows', - 'session_width', - 'session_height', - 'session_id', - 'session_created', - 'session_created_string', - 'session_attached', - 'session_grouped', - 'session_group', + "session_name", + "session_windows", + "session_width", + "session_height", + "session_id", + "session_created", + "session_created_string", + "session_attached", + "session_grouped", + "session_group", ] CLIENT_FORMATS = [ - 'client_cwd', - 'client_height', - 'client_width', - 'client_tty', - 'client_termname', - 'client_created', - 'client_created_string', - 'client_activity', - 'client_activity_string', - 'client_prefix', - 'client_utf8', - 'client_readonly', - 'client_session', - 'client_last_session', + "client_cwd", + "client_height", + "client_width", + "client_tty", + "client_termname", + "client_created", + "client_created_string", + "client_activity", + "client_activity_string", + "client_prefix", + "client_utf8", + "client_readonly", + "client_session", + "client_last_session", ] WINDOW_FORMATS = [ # format_window() - 'window_id', - 'window_name', - 'window_width', - 'window_height', - 'window_layout', - 'window_panes', + "window_id", + "window_name", + "window_width", + "window_height", + "window_layout", + "window_panes", # format_winlink() - 'window_index', - 'window_flags', - 'window_active', - 'window_bell_flag', - 'window_activity_flag', - 'window_silence_flag', + "window_index", + "window_flags", + "window_active", + "window_bell_flag", + "window_activity_flag", + "window_silence_flag", ] PANE_FORMATS = [ - 'history_size', - 'history_limit', - 'history_bytes', - 'pane_index', - 'pane_width', - 'pane_height', - 'pane_title', - 'pane_id', - 'pane_active', - 'pane_dead', - 'pane_in_mode', - 'pane_synchronized', - 'pane_tty', - 'pane_pid', - 'pane_start_command', - 'pane_start_path', - 'pane_current_path', - 'pane_current_command', - 'cursor_x', - 'cursor_y', - 'scroll_region_upper', - 'scroll_region_lower', - 'saved_cursor_x', - 'saved_cursor_y', - 'alternate_on', - 'alternate_saved_x', - 'alternate_saved_y', - 'cursor_flag', - 'insert_flag', - 'keypad_cursor_flag', - 'keypad_flag', - 'wrap_flag', - 'mouse_standard_flag', - 'mouse_button_flag', - 'mouse_any_flag', - 'mouse_utf8_flag', + "history_size", + "history_limit", + "history_bytes", + "pane_index", + "pane_width", + "pane_height", + "pane_title", + "pane_id", + "pane_active", + "pane_dead", + "pane_in_mode", + "pane_synchronized", + "pane_tty", + "pane_pid", + "pane_start_command", + "pane_start_path", + "pane_current_path", + "pane_current_command", + "cursor_x", + "cursor_y", + "scroll_region_upper", + "scroll_region_lower", + "saved_cursor_x", + "saved_cursor_y", + "alternate_on", + "alternate_saved_x", + "alternate_saved_y", + "cursor_flag", + "insert_flag", + "keypad_cursor_flag", + "keypad_flag", + "wrap_flag", + "mouse_standard_flag", + "mouse_button_flag", + "mouse_any_flag", + "mouse_utf8_flag", ] diff --git a/libtmux/pane.py b/libtmux/pane.py index 32f8ecbce..c229f8fb0 100644 --- a/libtmux/pane.py +++ b/libtmux/pane.py @@ -43,24 +43,24 @@ class Pane(TmuxMappingObject, TmuxRelationalObject): """ #: namespace used :class:`~libtmux.common.TmuxMappingObject` - formatter_prefix = 'pane_' + formatter_prefix = "pane_" def __init__(self, window=None, **kwargs): if not window: - raise ValueError('Pane must have ``Window`` object') + raise ValueError("Pane must have ``Window`` object") self.window = window self.session = self.window.session self.server = self.session.server - self._pane_id = kwargs['pane_id'] + self._pane_id = kwargs["pane_id"] self.server._update_panes() @property def _info(self, *args): - attrs = {'pane_id': self._pane_id} + attrs = {"pane_id": self._pane_id} # from https://github.com/serkanyersen/underscore.py def by(val, *args): @@ -86,8 +86,8 @@ def cmd(self, cmd, *args, **kwargs): ------- :class:`Server.cmd` """ - if not any(arg.startswith('-t') for arg in args): - args = ('-t', self.get('pane_id')) + args + if not any(arg.startswith("-t") for arg in args): + args = ("-t", self.get("pane_id")) + args return self.server.cmd(cmd, *args, **kwargs) @@ -109,12 +109,12 @@ def send_keys(self, cmd, enter=True, suppress_history=True, literal=False): literal : bool, optional Send keys literally, default True. """ - prefix = ' ' if suppress_history else '' + prefix = " " if suppress_history else "" if literal: - self.cmd('send-keys', '-l', prefix + cmd) + self.cmd("send-keys", "-l", prefix + cmd) else: - self.cmd('send-keys', prefix + cmd) + self.cmd("send-keys", prefix + cmd) if enter: self.enter() @@ -139,18 +139,18 @@ def display_message(self, cmd, get_text=False): :class:`None` """ if get_text: - return self.cmd('display-message', '-p', cmd).stdout + return self.cmd("display-message", "-p", cmd).stdout else: - self.cmd('display-message', cmd) + self.cmd("display-message", cmd) def clear(self): """Clear pane.""" - self.send_keys('reset') + self.send_keys("reset") def reset(self): """Reset and clear pane history.""" - self.cmd('send-keys', r'-R \; clear-history') + self.cmd("send-keys", r"-R \; clear-history") def split_window( self, attach=False, vertical=True, start_directory=None, percent=None @@ -174,7 +174,7 @@ def split_window( :class:`Pane` """ return self.window.split_window( - target=self.get('pane_id'), + target=self.get("pane_id"), start_directory=start_directory, attach=attach, vertical=vertical, @@ -228,12 +228,12 @@ def resize_pane(self, *args, **kwargs): exc.LibTmuxException """ - if 'height' in kwargs: - proc = self.cmd('resize-pane', '-y%s' % int(kwargs['height'])) - elif 'width' in kwargs: - proc = self.cmd('resize-pane', '-x%s' % int(kwargs['width'])) + if "height" in kwargs: + proc = self.cmd("resize-pane", "-y%s" % int(kwargs["height"])) + elif "width" in kwargs: + proc = self.cmd("resize-pane", "-x%s" % int(kwargs["width"])) else: - proc = self.cmd('resize-pane', args[0]) + proc = self.cmd("resize-pane", args[0]) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -247,7 +247,7 @@ def enter(self): ``$ tmux send-keys`` send Enter to the pane. """ - self.cmd('send-keys', 'Enter') + self.cmd("send-keys", "Enter") def capture_pane(self): """ @@ -259,7 +259,7 @@ def capture_pane(self): ------- :class:`list` """ - return self.cmd('capture-pane', '-p').stdout + return self.cmd("capture-pane", "-p").stdout def select_pane(self): """ @@ -273,7 +273,7 @@ def select_pane(self): ------- :class:`pane` """ - return self.window.select_pane(self.get('pane_id')) + return self.window.select_pane(self.get("pane_id")) def __repr__(self): - return "%s(%s %s)" % (self.__class__.__name__, self.get('pane_id'), self.window) + return "%s(%s %s)" % (self.__class__.__name__, self.get("pane_id"), self.window) diff --git a/libtmux/server.py b/libtmux/server.py index e871749e1..ac62ad546 100644 --- a/libtmux/server.py +++ b/libtmux/server.py @@ -65,9 +65,9 @@ class Server(TmuxRelationalObject, EnvironmentMixin): #: ``-2`` or ``-8`` colors = None #: unique child ID used by :class:`~libtmux.common.TmuxRelationalObject` - child_id_attribute = 'session_id' + child_id_attribute = "session_id" #: namespace used :class:`~libtmux.common.TmuxMappingObject` - formatter_prefix = 'server_' + formatter_prefix = "server_" def __init__( self, @@ -77,7 +77,7 @@ def __init__( colors=None, **kwargs ): - EnvironmentMixin.__init__(self, '-g') + EnvironmentMixin.__init__(self, "-g") self._windows = [] self._panes = [] @@ -110,18 +110,18 @@ def cmd(self, *args, **kwargs): args = list(args) if self.socket_name: - args.insert(0, '-L{}'.format(self.socket_name)) + args.insert(0, "-L{}".format(self.socket_name)) if self.socket_path: - args.insert(0, '-S{}'.format(self.socket_path)) + args.insert(0, "-S{}".format(self.socket_path)) if self.config_file: - args.insert(0, '-f{}'.format(self.config_file)) + args.insert(0, "-f{}".format(self.config_file)) if self.colors: if self.colors == 256: - args.insert(0, '-2') + args.insert(0, "-2") elif self.colors == 88: - args.insert(0, '-8') + args.insert(0, "-8") else: - raise ValueError('Server.colors must equal 88 or 256') + raise ValueError("Server.colors must equal 88 or 256") return tmux_cmd(*args, **kwargs) @@ -140,17 +140,17 @@ def _list_sessions(self): """ sformats = formats.SESSION_FORMATS - tmux_formats = ['#{%s}' % f for f in sformats] + tmux_formats = ["#{%s}" % f for f in sformats] - tmux_args = ('-F%s' % formats.FORMAT_SEPARATOR.join(tmux_formats),) # output + tmux_args = ("-F%s" % formats.FORMAT_SEPARATOR.join(tmux_formats),) # output - proc = self.cmd('list-sessions', *tmux_args) + proc = self.cmd("list-sessions", *tmux_args) if proc.stderr: raise exc.LibTmuxException(proc.stderr) sformats = formats.SESSION_FORMATS - tmux_formats = ['#{%s}' % format for format in sformats] + tmux_formats = ["#{%s}" % format for format in sformats] sessions = proc.stdout # combine format keys with values returned from ``tmux list-sessions`` @@ -204,14 +204,14 @@ def _list_windows(self): list of dict """ - wformats = ['session_name', 'session_id'] + formats.WINDOW_FORMATS - tmux_formats = ['#{%s}' % format for format in wformats] + wformats = ["session_name", "session_id"] + formats.WINDOW_FORMATS + tmux_formats = ["#{%s}" % format for format in wformats] print() proc = self.cmd( - 'list-windows', # ``tmux list-windows`` - '-a', - '-F%s' % formats.FORMAT_SEPARATOR.join(tmux_formats), # output + "list-windows", # ``tmux list-windows`` + "-a", + "-F%s" % formats.FORMAT_SEPARATOR.join(tmux_formats), # output ) if proc.stderr: @@ -219,7 +219,7 @@ def _list_windows(self): windows = proc.stdout - wformats = ['session_name', 'session_id'] + formats.WINDOW_FORMATS + wformats = ["session_name", "session_id"] + formats.WINDOW_FORMATS # combine format keys with values returned from ``tmux list-windows`` windows = [ @@ -232,8 +232,8 @@ def _list_windows(self): # tmux < 1.8 doesn't have window_id, use window_name for w in windows: - if 'window_id' not in w: - w['window_id'] = w['window_name'] + if "window_id" not in w: + w["window_id"] = w["window_name"] if self._windows: self._windows[:] = [] @@ -268,15 +268,15 @@ def _list_panes(self): """ pformats = [ - 'session_name', - 'session_id', - 'window_index', - 'window_id', - 'window_name', + "session_name", + "session_id", + "window_index", + "window_id", + "window_name", ] + formats.PANE_FORMATS - tmux_formats = [('#{%%s}%s' % formats.FORMAT_SEPARATOR) % f for f in pformats] + tmux_formats = [("#{%%s}%s" % formats.FORMAT_SEPARATOR) % f for f in pformats] - proc = self.cmd('list-panes', '-a', '-F%s' % ''.join(tmux_formats)) # output + proc = self.cmd("list-panes", "-a", "-F%s" % "".join(tmux_formats)) # output if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -284,11 +284,11 @@ def _list_panes(self): panes = proc.stdout pformats = [ - 'session_name', - 'session_id', - 'window_index', - 'window_id', - 'window_name', + "session_name", + "session_id", + "window_index", + "window_id", + "window_name", ] + formats.PANE_FORMATS # combine format keys with values returned from ``tmux list-panes`` @@ -300,7 +300,7 @@ def _list_panes(self): # clear up empty dict panes = [ dict( - (k, v) for k, v in window.items() if v or k == 'pane_current_path' + (k, v) for k, v in window.items() if v or k == "pane_current_path" ) # preserve pane_current_path, in case it entered a new process # where we may not get a cwd from. for window in panes @@ -338,10 +338,10 @@ def attached_sessions(self): attached_sessions = list() for session in sessions: - attached = session.get('session_attached') + attached = session.get("session_attached") # for now session_active is a unicode - if attached != '0': - logger.debug('session %s attached', session.get('name')) + if attached != "0": + logger.debug("session %s attached", session.get("name")) attached_sessions.append(session) else: continue @@ -371,10 +371,10 @@ def has_session(self, target_session, exact=True): """ session_check_name(target_session) - if exact and has_gte_version('2.1'): - target_session = '={}'.format(target_session) + if exact and has_gte_version("2.1"): + target_session = "={}".format(target_session) - proc = self.cmd('has-session', '-t%s' % target_session) + proc = self.cmd("has-session", "-t%s" % target_session) if not proc.returncode: return True @@ -383,7 +383,7 @@ def has_session(self, target_session, exact=True): def kill_server(self): """``$ tmux kill-server``.""" - self.cmd('kill-server') + self.cmd("kill-server") def kill_session(self, target_session=None): """ @@ -405,7 +405,7 @@ def kill_session(self, target_session=None): """ session_check_name(target_session) - proc = self.cmd('kill-session', '-t%s' % target_session) + proc = self.cmd("kill-session", "-t%s" % target_session) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -427,7 +427,7 @@ def switch_client(self, target_session): """ session_check_name(target_session) - proc = self.cmd('switch-client', '-t%s' % target_session) + proc = self.cmd("switch-client", "-t%s" % target_session) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -448,9 +448,9 @@ def attach_session(self, target_session=None): tmux_args = tuple() if target_session: - tmux_args += ('-t%s' % target_session,) + tmux_args += ("-t%s" % target_session,) - proc = self.cmd('attach-session', *tmux_args) + proc = self.cmd("attach-session", *tmux_args) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -518,45 +518,45 @@ def new_session( if self.has_session(session_name): if kill_session: - self.cmd('kill-session', '-t%s' % session_name) - logger.info('session %s exists. killed it.' % session_name) + self.cmd("kill-session", "-t%s" % session_name) + logger.info("session %s exists. killed it." % session_name) else: - raise exc.TmuxSessionExists('Session named %s exists' % session_name) + raise exc.TmuxSessionExists("Session named %s exists" % session_name) - logger.debug('creating session %s' % session_name) + logger.debug("creating session %s" % session_name) sformats = formats.SESSION_FORMATS - tmux_formats = ['#{%s}' % f for f in sformats] + tmux_formats = ["#{%s}" % f for f in sformats] - env = os.environ.get('TMUX') + env = os.environ.get("TMUX") if env: - del os.environ['TMUX'] + del os.environ["TMUX"] tmux_args = ( - '-s%s' % session_name, - '-P', - '-F%s' % formats.FORMAT_SEPARATOR.join(tmux_formats), # output + "-s%s" % session_name, + "-P", + "-F%s" % formats.FORMAT_SEPARATOR.join(tmux_formats), # output ) if not attach: - tmux_args += ('-d',) + tmux_args += ("-d",) if start_directory: - tmux_args += ('-c', start_directory) + tmux_args += ("-c", start_directory) if window_name: - tmux_args += ('-n', window_name) + tmux_args += ("-n", window_name) # tmux 2.6 gives unattached sessions a tiny default area # no need send in -x/-y if they're in a client already, though - if has_gte_version('2.6') and 'TMUX' not in os.environ: - tmux_args += ('-x', 800, '-y', 600) + if has_gte_version("2.6") and "TMUX" not in os.environ: + tmux_args += ("-x", 800, "-y", 600) if window_command: tmux_args += (window_command,) - proc = self.cmd('new-session', *tmux_args) + proc = self.cmd("new-session", *tmux_args) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -564,7 +564,7 @@ def new_session( session = proc.stdout[0] if env: - os.environ['TMUX'] = env + os.environ["TMUX"] = env # combine format keys with values returned from ``tmux list-windows`` session = dict(zip(sformats, session.split(formats.FORMAT_SEPARATOR))) diff --git a/libtmux/session.py b/libtmux/session.py index 90d755503..ffacd1f30 100644 --- a/libtmux/session.py +++ b/libtmux/session.py @@ -45,23 +45,23 @@ class Session(TmuxMappingObject, TmuxRelationalObject, EnvironmentMixin): """ #: unique child ID key for :class:`~libtmux.common.TmuxRelationalObject` - child_id_attribute = 'window_id' + child_id_attribute = "window_id" #: namespace used :class:`~libtmux.common.TmuxMappingObject` - formatter_prefix = 'session_' + formatter_prefix = "session_" def __init__(self, server=None, **kwargs): EnvironmentMixin.__init__(self) self.server = server - if 'session_id' not in kwargs: - raise ValueError('Session requires a `session_id`') - self._session_id = kwargs['session_id'] + if "session_id" not in kwargs: + raise ValueError("Session requires a `session_id`") + self._session_id = kwargs["session_id"] self.server._update_windows() @property def _info(self): - attrs = {'session_id': str(self._session_id)} + attrs = {"session_id": str(self._session_id)} def by(val): for key, value in attrs.items(): @@ -92,17 +92,17 @@ def cmd(self, *args, **kwargs): Renamed from ``.tmux`` to ``.cmd``. """ # if -t is not set in any arg yet - if not any('-t' in str(x) for x in args): + if not any("-t" in str(x) for x in args): # insert -t immediately after 1st arg, as per tmux format new_args = [args[0]] - new_args += ['-t', self.id] + new_args += ["-t", self.id] new_args += args[1:] args = new_args return self.server.cmd(*args, **kwargs) def attach_session(self): """Return ``$ tmux attach-session`` aka alias: ``$ tmux attach``.""" - proc = self.cmd('attach-session', '-t%s' % self.id) + proc = self.cmd("attach-session", "-t%s" % self.id) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -110,7 +110,7 @@ def attach_session(self): def kill_session(self): """``$ tmux kill-session``.""" - proc = self.cmd('kill-session', '-t%s' % self.id) + proc = self.cmd("kill-session", "-t%s" % self.id) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -124,7 +124,7 @@ def switch_client(self): :exc:`exc.LibTmuxException` """ - proc = self.cmd('switch-client', '-t%s' % self.id) + proc = self.cmd("switch-client", "-t%s" % self.id) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -148,10 +148,10 @@ def rename_session(self, new_name): """ session_check_name(new_name) - proc = self.cmd('rename-session', new_name) + proc = self.cmd("rename-session", new_name) if proc.stderr: - if has_version('2.7') and 'no current client' in proc.stderr: + if has_version("2.7") and "no current client" in proc.stderr: """tmux 2.7 raises "no current client" warning on BSD systems. Should be fixed next release: @@ -170,7 +170,7 @@ def new_window( window_name=None, start_directory=None, attach=True, - window_index='', + window_index="", window_shell=None, ): """ @@ -202,37 +202,37 @@ def new_window( ------- :class:`Window` """ - wformats = ['session_name', 'session_id'] + formats.WINDOW_FORMATS - tmux_formats = ['#{%s}' % f for f in wformats] + wformats = ["session_name", "session_id"] + formats.WINDOW_FORMATS + tmux_formats = ["#{%s}" % f for f in wformats] window_args = tuple() if not attach: - window_args += ('-d',) + window_args += ("-d",) - window_args += ('-P',) + window_args += ("-P",) if start_directory: # as of 2014-02-08 tmux 1.9-dev doesn't expand ~ in new-window -c. start_directory = os.path.expanduser(start_directory) - window_args += ('-c%s' % start_directory,) + window_args += ("-c%s" % start_directory,) window_args += ( '-F"%s"' % formats.FORMAT_SEPARATOR.join(tmux_formats), ) # output if window_name: - window_args += ('-n%s' % window_name,) + window_args += ("-n%s" % window_name,) window_args += ( # empty string for window_index will use the first one available - '-t%s:%s' + "-t%s:%s" % (self.id, window_index), ) if window_shell: window_args += (window_shell,) - proc = self.cmd('new-window', *window_args) + proc = self.cmd("new-window", *window_args) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -263,11 +263,11 @@ def kill_window(self, target_window=None): if target_window: if isinstance(target_window, int): - target = '-t%s:%d' % (self.name, target_window) + target = "-t%s:%d" % (self.name, target_window) else: - target = '-t%s' % target_window + target = "-t%s" % target_window - proc = self.cmd('kill-window', target) + proc = self.cmd("kill-window", target) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -277,7 +277,7 @@ def kill_window(self, target_window=None): def _list_windows(self): windows = self.server._update_windows()._windows - windows = [w for w in windows if w['session_id'] == self.id] + windows = [w for w in windows if w["session_id"] == self.id] return windows @@ -294,7 +294,7 @@ def list_windows(self): ------- :class:`Window` """ - windows = [w for w in self._windows if w['session_id'] == self._session_id] + windows = [w for w in self._windows if w["session_id"] == self._session_id] return [Window(session=self, **window) for window in windows] @@ -317,9 +317,9 @@ def attached_window(self): """ active_windows = [] for window in self._windows: - if 'window_active' in window: + if "window_active" in window: # for now window_active is a unicode - if window.get('window_active') == '1': + if window.get("window_active") == "1": active_windows.append(Window(session=self, **window)) else: continue @@ -328,11 +328,11 @@ def attached_window(self): return active_windows[0] else: raise exc.LibTmuxException( - 'multiple active windows found. %s' % active_windows + "multiple active windows found. %s" % active_windows ) if len(self._windows) == int(0): - raise exc.LibTmuxException('No Windows') + raise exc.LibTmuxException("No Windows") def select_window(self, target_window): """ @@ -358,9 +358,9 @@ def select_window(self, target_window): # Note that we also provide the session ID here, since cmd() # will not automatically add it as there is already a '-t' # argument provided. - target = '-t%s:%s' % (self._session_id, target_window) + target = "-t%s:%s" % (self._session_id, target_window) - proc = self.cmd('select-window', target) + proc = self.cmd("select-window", target) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -400,18 +400,18 @@ def set_option(self, option, value, _global=False): """ if isinstance(value, bool) and value: - value = 'on' + value = "on" elif isinstance(value, bool) and not value: - value = 'off' + value = "off" tmux_args = tuple() if _global: - tmux_args += ('-g',) + tmux_args += ("-g",) tmux_args += (option, value) - proc = self.cmd('set-option', *tmux_args) + proc = self.cmd("set-option", *tmux_args) if isinstance(proc.stderr, list) and len(proc.stderr): handle_option_error(proc.stderr[0]) @@ -443,15 +443,15 @@ def show_options(self, option=None, _global=False): tmux_args = tuple() if _global: - tmux_args += ('-g',) + tmux_args += ("-g",) if option: return self.show_option(option, _global=_global) else: - tmux_args += ('show-options',) + tmux_args += ("show-options",) session_options = self.cmd(*tmux_args).stdout - session_options = [tuple(item.split(' ')) for item in session_options] + session_options = [tuple(item.split(" ")) for item in session_options] session_options = dict(session_options) @@ -491,11 +491,11 @@ def show_option(self, option, _global=False): tmux_args = tuple() if _global: - tmux_args += ('-g',) + tmux_args += ("-g",) tmux_args += (option,) - cmd = self.cmd('show-options', *tmux_args) + cmd = self.cmd("show-options", *tmux_args) if isinstance(cmd.stderr, list) and len(cmd.stderr): handle_option_error(cmd.stderr[0]) @@ -503,7 +503,7 @@ def show_option(self, option, _global=False): if not len(cmd.stdout): return None - option = [item.split(' ') for item in cmd.stdout][0] + option = [item.split(" ") for item in cmd.stdout][0] if option[1].isdigit(): option = (option[0], int(option[1])) diff --git a/libtmux/test.py b/libtmux/test.py index caf56c70e..6cafb7f3c 100644 --- a/libtmux/test.py +++ b/libtmux/test.py @@ -7,13 +7,13 @@ logger = logging.getLogger(__name__) -TEST_SESSION_PREFIX = 'libtmux_' -RETRY_TIMEOUT_SECONDS = int(os.getenv('RETRY_TIMEOUT_SECONDS', 8)) +TEST_SESSION_PREFIX = "libtmux_" +RETRY_TIMEOUT_SECONDS = int(os.getenv("RETRY_TIMEOUT_SECONDS", 8)) namer = tempfile._RandomNameSequence() current_dir = os.path.abspath(os.path.dirname(__file__)) -example_dir = os.path.abspath(os.path.join(current_dir, '..', 'examples')) -fixtures_dir = os.path.realpath(os.path.join(current_dir, 'fixtures')) +example_dir = os.path.abspath(os.path.join(current_dir, "..", "examples")) +fixtures_dir = os.path.realpath(os.path.join(current_dir, "fixtures")) def retry(seconds=RETRY_TIMEOUT_SECONDS): @@ -127,8 +127,8 @@ def temp_session(server, *args, **kwargs): ... session.new_window(window_name='my window') """ - if 'session_name' in kwargs: - session_name = kwargs.pop('session_name') + if "session_name" in kwargs: + session_name = kwargs.pop("session_name") else: session_name = get_test_session_name(server) @@ -176,15 +176,15 @@ def temp_window(session, *args, **kwargs): ... my_pane = window.split_window() """ - if 'window_name' not in kwargs: + if "window_name" not in kwargs: window_name = get_test_window_name(session) else: - window_name = kwargs.pop('window_name') + window_name = kwargs.pop("window_name") window = session.new_window(window_name, *args, **kwargs) # Get ``window_id`` before returning it, it may be killed within context. - window_id = window.get('window_id') + window_id = window.get("window_id") try: yield session diff --git a/libtmux/window.py b/libtmux/window.py index c35c59fc9..a06d68f06 100644 --- a/libtmux/window.py +++ b/libtmux/window.py @@ -36,22 +36,22 @@ class Window(TmuxMappingObject, TmuxRelationalObject): """ #: unique child ID key for :class:`~libtmux.common.TmuxRelationalObject` - child_id_attribute = 'pane_id' + child_id_attribute = "pane_id" #: namespace used :class:`~libtmux.common.TmuxMappingObject` - formatter_prefix = 'window_' + formatter_prefix = "window_" def __init__(self, session=None, **kwargs): if not session: - raise ValueError('Window requires a Session, session=Session') + raise ValueError("Window requires a Session, session=Session") self.session = session self.server = self.session.server - if 'window_id' not in kwargs: - raise ValueError('Window requires a `window_id`') + if "window_id" not in kwargs: + raise ValueError("Window requires a `window_id`") - self._window_id = kwargs['window_id'] + self._window_id = kwargs["window_id"] def __repr__(self): return "%s(%s %s:%s, %s)" % ( @@ -65,7 +65,7 @@ def __repr__(self): @property def _info(self, *args): - attrs = {'window_id': self._window_id} + attrs = {"window_id": self._window_id} # from https://github.com/serkanyersen/underscore.py def by(val, *args): @@ -81,7 +81,7 @@ def by(val, *args): # If a window_shell option was configured which results in # a short-lived process, the window id is @0. Use that instead of # self._window_id - if len(ret) == 0 and self.server._windows[0]['window_id'] == '@0': + if len(ret) == 0 and self.server._windows[0]["window_id"] == "@0": ret = self.server._windows return ret[0] @@ -103,8 +103,8 @@ def cmd(self, cmd, *args, **kwargs): Renamed from ``.tmux`` to ``.cmd``. """ - if not any(arg.startswith('-t') for arg in args): - args = ('-t', self.id) + args + if not any(arg.startswith("-t") for arg in args): + args = ("-t", self.id) + args return self.server.cmd(cmd, *args, **kwargs) @@ -137,7 +137,7 @@ def select_layout(self, layout=None): 'custom' custom dimensions (see :term:`tmux(1)` manpages). """ - cmd = ['select-layout', '-t%s:%s' % (self.get('session_id'), self.index)] + cmd = ["select-layout", "-t%s:%s" % (self.get("session_id"), self.index)] if layout: # tmux allows select-layout without args cmd.append(layout) @@ -168,13 +168,13 @@ def set_window_option(self, option, value): self.server._update_windows() if isinstance(value, bool) and value: - value = 'on' + value = "on" elif isinstance(value, bool) and not value: - value = 'off' + value = "off" cmd = self.cmd( - 'set-window-option', - '-t%s:%s' % (self.get('session_id'), self.index), + "set-window-option", + "-t%s:%s" % (self.get("session_id"), self.index), # '-t%s' % self.id, option, value, @@ -205,12 +205,12 @@ def show_window_options(self, option=None, g=False): tmux_args = tuple() if g: - tmux_args += ('-g',) + tmux_args += ("-g",) if option: return self.show_window_option(option, g=g) else: - tmux_args += ('show-window-options',) + tmux_args += ("show-window-options",) cmd = self.cmd(*tmux_args).stdout # The shlex.split function splits the args at spaces, while also @@ -251,11 +251,11 @@ def show_window_option(self, option, g=False): tmux_args = tuple() if g: - tmux_args += ('-g',) + tmux_args += ("-g",) tmux_args += (option,) - cmd = self.cmd('show-window-options', *tmux_args) + cmd = self.cmd("show-window-options", *tmux_args) if len(cmd.stderr): handle_option_error(cmd.stderr[0]) @@ -283,12 +283,12 @@ def rename_window(self, new_name): import shlex lex = shlex.shlex(new_name) - lex.escape = ' ' + lex.escape = " " lex.whitespace_split = False try: - self.cmd('rename-window', new_name) - self['window_name'] = new_name + self.cmd("rename-window", new_name) + self["window_name"] = new_name except Exception as e: logger.error(e) @@ -300,9 +300,9 @@ def kill_window(self): """Kill the current :class:`Window` object. ``$ tmux kill-window``.""" proc = self.cmd( - 'kill-window', + "kill-window", # '-t:%s' % self.id - '-t%s:%s' % (self.get('session_id'), self.index), + "-t%s:%s" % (self.get("session_id"), self.index), ) if proc.stderr: @@ -323,11 +323,11 @@ def move_window(self, destination="", session=None): the ``target session`` or index to move the window to, default: current session. """ - session = session or self.get('session_id') + session = session or self.get("session_id") proc = self.cmd( - 'move-window', - '-s%s:%s' % (self.get('session_id'), self.index), - '-t%s:%s' % (session, destination), + "move-window", + "-s%s:%s" % (self.get("session_id"), self.index), + "-t%s:%s" % (session, destination), ) if proc.stderr: @@ -363,10 +363,10 @@ def select_pane(self, target_pane): :class:`Pane` """ - if target_pane in ['-l', '-U', '-D', '-L', '-R']: - proc = self.cmd('select-pane', '-t%s' % self.id, target_pane) + if target_pane in ["-l", "-U", "-D", "-L", "-R"]: + proc = self.cmd("select-pane", "-t%s" % self.id, target_pane) else: - proc = self.cmd('select-pane', '-t%s' % target_pane) + proc = self.cmd("select-pane", "-t%s" % target_pane) if proc.stderr: raise exc.LibTmuxException(proc.stderr) @@ -375,7 +375,7 @@ def select_pane(self, target_pane): def last_pane(self): """Return last pane.""" - return self.select_pane('-l') + return self.select_pane("-l") def split_window( self, @@ -429,49 +429,49 @@ def split_window( target window, pass in ``attach=False``. """ pformats = [ - 'session_name', - 'session_id', - 'window_index', - 'window_id', + "session_name", + "session_id", + "window_index", + "window_id", ] + formats.PANE_FORMATS - tmux_formats = [(f'#{{{f}}}{formats.FORMAT_SEPARATOR}') for f in pformats] + tmux_formats = [(f"#{{{f}}}{formats.FORMAT_SEPARATOR}") for f in pformats] # '-t%s' % self.attached_pane.get('pane_id'), # 2013-10-18 LOOK AT THIS, rm'd it.. tmux_args = tuple() if target: - tmux_args += ('-t%s' % target,) + tmux_args += ("-t%s" % target,) else: - tmux_args += ('-t%s' % self.panes[0].get('pane_id'),) + tmux_args += ("-t%s" % self.panes[0].get("pane_id"),) if vertical: - tmux_args += ('-v',) + tmux_args += ("-v",) else: - tmux_args += ('-h',) + tmux_args += ("-h",) if percent is not None: - tmux_args += ('-p %d' % percent,) + tmux_args += ("-p %d" % percent,) - tmux_args += ('-P', '-F%s' % ''.join(tmux_formats)) # output + tmux_args += ("-P", "-F%s" % "".join(tmux_formats)) # output if start_directory: # as of 2014-02-08 tmux 1.9-dev doesn't expand ~ in new-window -c. start_directory = os.path.expanduser(start_directory) - tmux_args += ('-c%s' % start_directory,) + tmux_args += ("-c%s" % start_directory,) if not attach: - tmux_args += ('-d',) + tmux_args += ("-d",) if shell: tmux_args += (shell,) - pane = self.cmd('split-window', *tmux_args) + pane = self.cmd("split-window", *tmux_args) # tmux < 1.7. This is added in 1.7. if pane.stderr: raise exc.LibTmuxException(pane.stderr) - if 'pane too small' in pane.stderr: + if "pane too small" in pane.stderr: pass raise exc.LibTmuxException(pane.stderr, self._info, self.panes) @@ -495,9 +495,9 @@ def attached_pane(self): :class:`Pane` """ for pane in self._panes: - if 'pane_active' in pane: + if "pane_active" in pane: # for now pane_active is a unicode - if pane.get('pane_active') == '1': + if pane.get("pane_active") == "1": return Pane(window=self, **pane) else: continue @@ -507,8 +507,8 @@ def attached_pane(self): def _list_panes(self): panes = self.server._update_panes()._panes - panes = [p for p in panes if p['session_id'] == self.get('session_id')] - panes = [p for p in panes if p['window_id'] == self.id] + panes = [p for p in panes if p["session_id"] == self.get("session_id")] + panes = [p for p in panes if p["window_id"] == self.id] return panes @property diff --git a/pyproject.toml b/pyproject.toml index 974f492af..0e2786e28 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,3 @@ -[tool.black] -skip-string-normalization = true - [tool.poetry] name = "libtmux" version = "0.11.0b0" diff --git a/tests/conftest.py b/tests/conftest.py index e72c8c961..0ce651b5e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -20,29 +20,29 @@ def clear_env(monkeypatch): if not any( needle in k.lower() for needle in [ - 'window', - 'tmux', - 'pane', - 'session', - 'pytest', - 'path', - 'pwd', - 'shell', - 'home', - 'xdg', - 'disable_auto_title', - 'lang', - 'term', + "window", + "tmux", + "pane", + "session", + "pytest", + "path", + "pwd", + "shell", + "home", + "xdg", + "disable_auto_title", + "lang", + "term", ] ): monkeypatch.delenv(k) -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def server(request, monkeypatch): t = Server() - t.socket_name = 'tmuxp_test%s' % next(namer) + t.socket_name = "tmuxp_test%s" % next(namer) def fin(): t.kill_server() @@ -52,18 +52,18 @@ def fin(): return t -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def session(request, server): - session_name = 'tmuxp' + session_name = "tmuxp" if not server.has_session(session_name): - server.cmd('new-session', '-d', '-s', session_name) + server.cmd("new-session", "-d", "-s", session_name) # find current sessions prefixed with tmuxp old_test_sessions = [ - s.get('session_name') + s.get("session_name") for s in server._sessions - if s.get('session_name').startswith(TEST_SESSION_PREFIX) + if s.get("session_name").startswith(TEST_SESSION_PREFIX) ] TEST_SESSION_NAME = get_test_session_name(server=server) @@ -78,22 +78,22 @@ def session(request, server): the newly created session for that testcase. """ try: - server.switch_client(session.get('session_id')) + server.switch_client(session.get("session_id")) pass except exc.LibTmuxException: # server.attach_session(session.get('session_id')) pass for old_test_session in old_test_sessions: - logger.debug('Old test test session %s found. Killing it.' % old_test_session) + logger.debug("Old test test session %s found. Killing it." % old_test_session) server.kill_session(old_test_session) - assert TEST_SESSION_NAME == session.get('session_name') - assert TEST_SESSION_NAME != 'tmuxp' + assert TEST_SESSION_NAME == session.get("session_name") + assert TEST_SESSION_NAME != "tmuxp" return session @pytest.fixture() def tmpdir(tmpdir_factory): - fn = tmpdir_factory.mktemp('tmuxp') + fn = tmpdir_factory.mktemp("tmuxp") return fn diff --git a/tests/test_common.py b/tests/test_common.py index cf90b6271..9d529f4b8 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -24,71 +24,71 @@ ) from libtmux.exc import BadSessionName, LibTmuxException, TmuxCommandNotFound -version_regex = re.compile(r'([0-9]\.[0-9])|(master)') +version_regex = re.compile(r"([0-9]\.[0-9])|(master)") def test_allows_master_version(monkeypatch): def mock_tmux_cmd(param): class Hi(object): - stdout = ['tmux master'] + stdout = ["tmux master"] stderr = None return Hi() - monkeypatch.setattr(libtmux.common, 'tmux_cmd', mock_tmux_cmd) + monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) assert has_minimum_version() assert has_gte_version(TMUX_MIN_VERSION) assert has_gt_version(TMUX_MAX_VERSION), "Greater than the max-supported version" assert ( - '%s-master' % TMUX_MAX_VERSION == get_version() + "%s-master" % TMUX_MAX_VERSION == get_version() ), "Is the latest supported version with -master appended" def test_allows_next_version(monkeypatch): def mock_tmux_cmd(param): class Hi(object): - stdout = ['tmux next-2.9'] + stdout = ["tmux next-2.9"] stderr = None return Hi() - monkeypatch.setattr(libtmux.common, 'tmux_cmd', mock_tmux_cmd) + monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) assert has_minimum_version() assert has_gte_version(TMUX_MIN_VERSION) assert has_gt_version(TMUX_MAX_VERSION), "Greater than the max-supported version" - assert '2.9' == get_version() + assert "2.9" == get_version() def test_get_version_openbsd(monkeypatch): def mock_tmux_cmd(param): class Hi(object): - stderr = ['tmux: unknown option -- V'] + stderr = ["tmux: unknown option -- V"] return Hi() - monkeypatch.setattr(libtmux.common, 'tmux_cmd', mock_tmux_cmd) - monkeypatch.setattr(sys, 'platform', 'openbsd 5.2') + monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) + monkeypatch.setattr(sys, "platform", "openbsd 5.2") assert has_minimum_version() assert has_gte_version(TMUX_MIN_VERSION) assert has_gt_version(TMUX_MAX_VERSION), "Greater than the max-supported version" assert ( - '%s-openbsd' % TMUX_MAX_VERSION == get_version() + "%s-openbsd" % TMUX_MAX_VERSION == get_version() ), "Is the latest supported version with -openbsd appended" def test_get_version_too_low(monkeypatch): def mock_tmux_cmd(param): class Hi(object): - stderr = ['tmux: unknown option -- V'] + stderr = ["tmux: unknown option -- V"] return Hi() - monkeypatch.setattr(libtmux.common, 'tmux_cmd', mock_tmux_cmd) + monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) with pytest.raises(LibTmuxException) as exc_info: get_version() - exc_info.match('is running tmux 1.3 or earlier') + exc_info.match("is running tmux 1.3 or earlier") def test_ignores_letter_versions(): @@ -100,31 +100,31 @@ def test_ignores_letter_versions(): allow letters. """ - result = has_minimum_version('1.9a') + result = has_minimum_version("1.9a") assert result - result = has_minimum_version('1.8a') + result = has_minimum_version("1.8a") assert result # Should not throw - assert type(has_version('1.8')) is bool - assert type(has_version('1.8a')) is bool - assert type(has_version('1.9a')) is bool + assert type(has_version("1.8")) is bool + assert type(has_version("1.8a")) is bool + assert type(has_version("1.9a")) is bool def test_error_version_less_1_7(monkeypatch): def mock_get_version(): - return LooseVersion('1.7') + return LooseVersion("1.7") - monkeypatch.setattr(libtmux.common, 'get_version', mock_get_version) + monkeypatch.setattr(libtmux.common, "get_version", mock_get_version) with pytest.raises(LibTmuxException) as excinfo: has_minimum_version() - excinfo.match(r'libtmux only supports') + excinfo.match(r"libtmux only supports") with pytest.raises(LibTmuxException) as excinfo: has_minimum_version() - excinfo.match(r'libtmux only supports') + excinfo.match(r"libtmux only supports") def test_has_version(): @@ -132,64 +132,64 @@ def test_has_version(): def test_has_gt_version(): - assert has_gt_version('1.6') - assert has_gt_version('1.6b') + assert has_gt_version("1.6") + assert has_gt_version("1.6b") - assert not has_gt_version('4.0') - assert not has_gt_version('4.0b') + assert not has_gt_version("4.0") + assert not has_gt_version("4.0b") def test_has_gte_version(): - assert has_gte_version('1.6') - assert has_gte_version('1.6b') + assert has_gte_version("1.6") + assert has_gte_version("1.6b") assert has_gte_version(str(get_version())) - assert not has_gte_version('4.0') - assert not has_gte_version('4.0b') + assert not has_gte_version("4.0") + assert not has_gte_version("4.0b") def test_has_lt_version(): - assert has_lt_version('4.0a') - assert has_lt_version('4.0') + assert has_lt_version("4.0a") + assert has_lt_version("4.0") - assert not has_lt_version('1.7') + assert not has_lt_version("1.7") assert not has_lt_version(str(get_version())) def test_has_lte_version(): - assert has_lte_version('4.0a') - assert has_lte_version('4.0') + assert has_lte_version("4.0a") + assert has_lte_version("4.0") assert has_lte_version(str(get_version())) - assert not has_lte_version('1.7') - assert not has_lte_version('1.7b') + assert not has_lte_version("1.7") + assert not has_lte_version("1.7b") def test_which_no_bin_found(): - assert which('top') - assert which('top', default_paths=[]) - assert not which('top', default_paths=[], append_env_path=False) - assert not which('top', default_paths=['/'], append_env_path=False) + assert which("top") + assert which("top", default_paths=[]) + assert not which("top", default_paths=[], append_env_path=False) + assert not which("top", default_paths=["/"], append_env_path=False) def test_tmux_cmd_raises_on_not_found(): with pytest.raises(TmuxCommandNotFound): - tmux_cmd('-V', tmux_search_paths=[], append_env_path=False) + tmux_cmd("-V", tmux_search_paths=[], append_env_path=False) - tmux_cmd('-V') + tmux_cmd("-V") def test_tmux_cmd_unicode(session): - session.cmd('new-window', '-t', 3, '-n', 'юникод', '-F', u'Ελληνικά') + session.cmd("new-window", "-t", 3, "-n", "юникод", "-F", "Ελληνικά") @pytest.mark.parametrize( "session_name,raises,exc_msg_regex", [ - ('', True, 'may not be empty'), - (None, True, 'may not be empty'), - ("my great session.", True, 'may not contain periods'), - ("name: great session", True, 'may not contain colons'), + ("", True, "may not be empty"), + (None, True, "may not be empty"), + ("my great session.", True, "may not contain periods"), + ("name: great session", True, "may not contain colons"), ("new great session", False, None), ("ajf8a3fa83fads,,,a", False, None), ], diff --git a/tests/test_pane.py b/tests/test_pane.py index f3535a9cd..a5adc3ddf 100644 --- a/tests/test_pane.py +++ b/tests/test_pane.py @@ -8,52 +8,52 @@ def test_resize_pane(session): """Test Pane.resize_pane().""" window = session.attached_window - window.rename_window('test_resize_pane') + window.rename_window("test_resize_pane") pane1 = window.attached_pane - pane1_height = pane1['pane_height'] + pane1_height = pane1["pane_height"] window.split_window() pane1.resize_pane(height=4) - assert pane1['pane_height'] != pane1_height - assert int(pane1['pane_height']) == 4 + assert pane1["pane_height"] != pane1_height + assert int(pane1["pane_height"]) == 4 pane1.resize_pane(height=3) - assert int(pane1['pane_height']) == 3 + assert int(pane1["pane_height"]) == 3 def test_send_keys(session): pane = session.attached_window.attached_pane - pane.send_keys('c-c', literal=True) + pane.send_keys("c-c", literal=True) - pane_contents = '\n'.join(pane.cmd('capture-pane', '-p').stdout) - assert 'c-c' in pane_contents + pane_contents = "\n".join(pane.cmd("capture-pane", "-p").stdout) + assert "c-c" in pane_contents - pane.send_keys('c-a', literal=False) - assert 'c-a' not in pane_contents, 'should not print to pane' + pane.send_keys("c-a", literal=False) + assert "c-a" not in pane_contents, "should not print to pane" def test_set_height(session): - window = session.new_window(window_name='test_set_height') + window = session.new_window(window_name="test_set_height") window.split_window() pane1 = window.attached_pane - pane1_height = pane1['pane_height'] + pane1_height = pane1["pane_height"] pane1.set_height(4) - assert pane1['pane_height'] != pane1_height - assert int(pane1['pane_height']) == 4 + assert pane1["pane_height"] != pane1_height + assert int(pane1["pane_height"]) == 4 def test_set_width(session): - window = session.new_window(window_name='test_set_width') + window = session.new_window(window_name="test_set_width") window.split_window() - window.select_layout('main-vertical') + window.select_layout("main-vertical") pane1 = window.attached_pane - pane1_width = pane1['pane_width'] + pane1_width = pane1["pane_width"] pane1.set_width(10) - assert pane1['pane_width'] != pane1_width - assert int(pane1['pane_width']) == 10 + assert pane1["pane_width"] != pane1_width + assert int(pane1["pane_width"]) == 10 pane1.reset() diff --git a/tests/test_server.py b/tests/test_server.py index 29d79df55..04ee23abc 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -8,8 +8,8 @@ def test_has_session(server, session): - assert server.has_session(session.get('session_name')) - assert not server.has_session('asdf2314324321') + assert server.has_session(session.get("session_name")) + assert not server.has_session("asdf2314324321") def test_socket_name(server): @@ -19,22 +19,22 @@ def test_socket_name(server): env TMUX_TMPDIR or /tmp if unset.) """ - myserver = Server(socket_name='test') + myserver = Server(socket_name="test") - assert myserver.socket_name == 'test' + assert myserver.socket_name == "test" def test_socket_path(server): """``-S`` socket_path (alternative path for server socket).""" - myserver = Server(socket_path='test') + myserver = Server(socket_path="test") - assert myserver.socket_path == 'test' + assert myserver.socket_path == "test" def test_config(server): """``-f`` file for tmux(1) configuration.""" - myserver = Server(config_file='test') - assert myserver.config_file == 'test' + myserver = Server(config_file="test") + assert myserver.config_file == "test" def test_256_colors(server): @@ -42,22 +42,22 @@ def test_256_colors(server): assert myserver.colors == 256 print(myserver.colors) - proc = myserver.cmd('list-sessions') + proc = myserver.cmd("list-sessions") - print('list-sessions', proc) + print("list-sessions", proc) - assert '-2' in proc.cmd - assert '-8' not in proc.cmd + assert "-2" in proc.cmd + assert "-8" not in proc.cmd def test_88_colors(server): myserver = Server(colors=88) assert myserver.colors == 88 - proc = myserver.cmd('list-sessions') + proc = myserver.cmd("list-sessions") - assert '-8' in proc.cmd - assert '-2' not in proc.cmd + assert "-8" in proc.cmd + assert "-2" not in proc.cmd def test_show_environment(server): @@ -68,18 +68,18 @@ def test_show_environment(server): def test_set_show_environment_single(server, session): """Set environment then Server.show_environment(key).""" - server.set_environment('FOO', 'BAR') - assert 'BAR' == server.show_environment('FOO') + server.set_environment("FOO", "BAR") + assert "BAR" == server.show_environment("FOO") - server.set_environment('FOO', 'DAR') - assert 'DAR' == server.show_environment('FOO') + server.set_environment("FOO", "DAR") + assert "DAR" == server.show_environment("FOO") - assert 'DAR' == server.show_environment()['FOO'] + assert "DAR" == server.show_environment()["FOO"] def test_show_environment_not_set(server): """Unset environment variable returns None.""" - assert server.show_environment('BAR') is None + assert server.show_environment("BAR") is None def test_new_session(server): @@ -92,14 +92,14 @@ def test_new_session(server): def test_new_session_shell(server): """Server.new_session creates and returns valid session running with specified command""" - cmd = 'sleep 1m' + cmd = "sleep 1m" mysession = server.new_session("test_new_session", window_command=cmd) window = mysession.list_windows()[0] pane = window.list_panes()[0] assert mysession.get("session_name") == "test_new_session" assert server.has_session("test_new_session") - if has_gte_version('3.2'): - assert pane.get('pane_start_command').replace('"', '') == cmd + if has_gte_version("3.2"): + assert pane.get("pane_start_command").replace('"', "") == cmd else: - assert pane.get('pane_start_command') == cmd + assert pane.get("pane_start_command") == cmd diff --git a/tests/test_session.py b/tests/test_session.py index 99d4aa63e..3638c16cf 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -12,21 +12,21 @@ def test_has_session(server, session): """Server.has_session returns True if has session_name exists.""" - TEST_SESSION_NAME = session.get('session_name') + TEST_SESSION_NAME = session.get("session_name") assert server.has_session(TEST_SESSION_NAME) - if has_gte_version('2.1'): + if has_gte_version("2.1"): assert not server.has_session(TEST_SESSION_NAME[:-2]) assert server.has_session(TEST_SESSION_NAME[:-2], exact=False) - assert not server.has_session('asdf2314324321') + assert not server.has_session("asdf2314324321") def test_select_window(session): """Session.select_window moves window.""" # get the current window_base_index, since different user tmux config # may start at 0 or 1, or whatever they want. - window_base_index = int(session.attached_window.get('window_index')) + window_base_index = int(session.attached_window.get("window_index")) - session.new_window(window_name='test_window') + session.new_window(window_name="test_window") window_count = len(session._windows) assert window_count >= 2 # 2 or more windows @@ -60,7 +60,7 @@ def test_select_window_returns_Window(session): window_count = len(session._windows) assert len(session._windows) == window_count - window_base_index = int(session.attached_window.get('window_index')) + window_base_index = int(session.attached_window.get("window_index")) assert isinstance(session.select_window(window_base_index), Window) @@ -77,12 +77,12 @@ def test_attached_pane(session): def test_session_rename(session): """Session.rename_session renames session.""" - TEST_SESSION_NAME = session.get('session_name') - test_name = 'testingdis_sessname' + TEST_SESSION_NAME = session.get("session_name") + test_name = "testingdis_sessname" session.rename_session(test_name) - assert session.get('session_name') == test_name + assert session.get("session_name") == test_name session.rename_session(TEST_SESSION_NAME) - assert session.get('session_name') == TEST_SESSION_NAME + assert session.get("session_name") == TEST_SESSION_NAME def test_new_session(server): @@ -91,7 +91,7 @@ def test_new_session(server): new_session = server.new_session(session_name=new_session_name, detach=True) assert isinstance(new_session, Session) - assert new_session.get('session_name') == new_session_name + assert new_session.get("session_name") == new_session_name def test_show_options(session): @@ -104,58 +104,58 @@ def test_show_options(session): def test_set_show_options_single(session): """Set option then Session.show_options(key).""" - session.set_option('history-limit', 20) - assert session.show_options('history-limit') == 20 + session.set_option("history-limit", 20) + assert session.show_options("history-limit") == 20 - session.set_option('history-limit', 40) - assert session.show_options('history-limit') == 40 + session.set_option("history-limit", 40) + assert session.show_options("history-limit") == 40 - assert session.show_options()['history-limit'] == 40 + assert session.show_options()["history-limit"] == 40 def test_set_show_option(session): """Set option then Session.show_option(key).""" - session.set_option('history-limit', 20) - assert session.show_option('history-limit') == 20 + session.set_option("history-limit", 20) + assert session.show_option("history-limit") == 20 - session.set_option('history-limit', 40) + session.set_option("history-limit", 40) - assert session.show_option('history-limit') == 40 + assert session.show_option("history-limit") == 40 def test_empty_session_option_returns_None(session): - assert session.show_option('default-shell') is None + assert session.show_option("default-shell") is None def test_show_option_unknown(session): """Session.show_option raises UnknownOption for invalid option.""" cmd_exception = exc.UnknownOption - if has_gte_version('3.0'): + if has_gte_version("3.0"): cmd_exception = exc.InvalidOption with pytest.raises(cmd_exception): - session.show_option('moooz') + session.show_option("moooz") def test_show_option_ambiguous(session): """Session.show_option raises AmbiguousOption for ambiguous option.""" with pytest.raises(exc.AmbiguousOption): - session.show_option('default-') + session.show_option("default-") def test_set_option_ambigous(session): """Session.set_option raises AmbiguousOption for invalid option.""" with pytest.raises(exc.AmbiguousOption): - session.set_option('default-', 43) + session.set_option("default-", 43) def test_set_option_invalid(session): """Session.set_option raises UnknownOption for invalid option.""" - if has_gte_version('2.4'): + if has_gte_version("2.4"): with pytest.raises(exc.InvalidOption): - session.set_option('afewewfew', 43) + session.set_option("afewewfew", 43) else: with pytest.raises(exc.UnknownOption): - session.set_option('afewewfew', 43) + session.set_option("afewewfew", 43) def test_show_environment(session): @@ -168,44 +168,44 @@ def test_show_environment(session): def test_set_show_environment_single(session): """Set environment then Session.show_environment(key).""" - session.set_environment('FOO', 'BAR') - assert session.show_environment('FOO') == 'BAR' + session.set_environment("FOO", "BAR") + assert session.show_environment("FOO") == "BAR" - session.set_environment('FOO', 'DAR') - assert session.show_environment('FOO') == 'DAR' + session.set_environment("FOO", "DAR") + assert session.show_environment("FOO") == "DAR" - assert session.show_environment()['FOO'] == 'DAR' + assert session.show_environment()["FOO"] == "DAR" def test_show_environment_not_set(session): """Not set environment variable returns None.""" - assert session.show_environment('BAR') is None + assert session.show_environment("BAR") is None def test_remove_environment(session): """Remove environment variable.""" - assert session.show_environment('BAM') is None - session.set_environment('BAM', 'OK') - assert session.show_environment('BAM') == 'OK' - session.remove_environment('BAM') - assert session.show_environment('BAM') is None + assert session.show_environment("BAM") is None + session.set_environment("BAM", "OK") + assert session.show_environment("BAM") == "OK" + session.remove_environment("BAM") + assert session.show_environment("BAM") is None def test_unset_environment(session): """Unset environment variable.""" - assert session.show_environment('BAM') is None - session.set_environment('BAM', 'OK') - assert session.show_environment('BAM') == 'OK' - session.unset_environment('BAM') - assert session.show_environment('BAM') is None + assert session.show_environment("BAM") is None + session.set_environment("BAM", "OK") + assert session.show_environment("BAM") == "OK" + session.unset_environment("BAM") + assert session.show_environment("BAM") is None @pytest.mark.parametrize( "session_name,raises", - [('hey.period', True), ('hey:its a colon', True), ('hey moo', False)], + [("hey.period", True), ("hey:its a colon", True), ("hey moo", False)], ) def test_periods_raise_badsessionname(server, session, session_name, raises): - new_name = session_name + 'moo' # used for rename / switch + new_name = session_name + "moo" # used for rename / switch if raises: with pytest.raises(exc.BadSessionName): session.rename_session(new_name) @@ -232,8 +232,8 @@ def test_periods_raise_badsessionname(server, session, session_name, raises): def test_cmd_inserts_sesion_id(session): current_session_id = session.id - last_arg = 'last-arg' - cmd = session.cmd('not-a-command', last_arg) - assert '-t' in cmd.cmd + last_arg = "last-arg" + cmd = session.cmd("not-a-command", last_arg) + assert "-t" in cmd.cmd assert current_session_id in cmd.cmd assert cmd.cmd[-1] == last_arg diff --git a/tests/test_tmuxobject.py b/tests/test_tmuxobject.py index c94036c50..788a29bf4 100644 --- a/tests/test_tmuxobject.py +++ b/tests/test_tmuxobject.py @@ -14,24 +14,24 @@ def test_find_where(server, session): """Test that find_where() retrieves single matching object.""" # server.find_where for session in server.sessions: - session_id = session.get('session_id') + session_id = session.get("session_id") - assert server.find_where({'session_id': session_id}) == session - assert isinstance(server.find_where({'session_id': session_id}), Session) + assert server.find_where({"session_id": session_id}) == session + assert isinstance(server.find_where({"session_id": session_id}), Session) # session.find_where for window in session.windows: - window_id = window.get('window_id') + window_id = window.get("window_id") - assert session.find_where({'window_id': window_id}) == window - assert isinstance(session.find_where({'window_id': window_id}), Window) + assert session.find_where({"window_id": window_id}) == window + assert isinstance(session.find_where({"window_id": window_id}), Window) # window.find_where for pane in window.panes: - pane_id = pane.get('pane_id') + pane_id = pane.get("pane_id") - assert window.find_where({'pane_id': pane_id}) == pane - assert isinstance(window.find_where({'pane_id': pane_id}), Pane) + assert window.find_where({"pane_id": pane_id}) == pane + assert isinstance(window.find_where({"pane_id": pane_id}), Pane) def test_find_where_None(server, session): @@ -43,17 +43,17 @@ def test_find_where_None(server, session): if not server.has_session(nonexistant_session): break - assert server.find_where({'session_name': nonexistant_session}) is None + assert server.find_where({"session_name": nonexistant_session}) is None def test_find_where_multiple_infos(server, session): """.find_where returns objects with multiple attributes.""" for session in server.sessions: - session_id = session.get('session_id') - session_name = session.get('session_name') + session_id = session.get("session_id") + session_name = session.get("session_name") find_where = server.find_where( - {'session_id': session_id, 'session_name': session_name} + {"session_id": session_id, "session_name": session_name} ) assert find_where == session @@ -61,11 +61,11 @@ def test_find_where_multiple_infos(server, session): # session.find_where for window in session.windows: - window_id = window.get('window_id') - window_index = window.get('window_index') + window_id = window.get("window_id") + window_index = window.get("window_index") find_where = session.find_where( - {'window_id': window_id, 'window_index': window_index} + {"window_id": window_id, "window_index": window_index} ) assert find_where == window @@ -73,11 +73,11 @@ def test_find_where_multiple_infos(server, session): # window.find_where for pane in window.panes: - pane_id = pane.get('pane_id') - pane_tty = pane.get('pane_tty') + pane_id = pane.get("pane_id") + pane_tty = pane.get("pane_tty") find_where = window.find_where( - {'pane_id': pane_id, 'pane_tty': pane_tty} + {"pane_id": pane_id, "pane_tty": pane_tty} ) assert find_where == pane @@ -91,9 +91,9 @@ def test_where(server, session): window.split_window() # create second pane for session in server.sessions: - session_id = session.get('session_id') - session_name = session.get('session_name') - where = server.where({'session_id': session_id, 'session_name': session_name}) + session_id = session.get("session_id") + session_name = session.get("session_name") + where = server.where({"session_id": session_id, "session_name": session_name}) assert len(where) == 1 assert isinstance(where, list) @@ -102,11 +102,11 @@ def test_where(server, session): # session.where for window in session.windows: - window_id = window.get('window_id') - window_index = window.get('window_index') + window_id = window.get("window_id") + window_index = window.get("window_index") where = session.where( - {'window_id': window_id, 'window_index': window_index} + {"window_id": window_id, "window_index": window_index} ) assert len(where) == 1 @@ -116,10 +116,10 @@ def test_where(server, session): # window.where for pane in window.panes: - pane_id = pane.get('pane_id') - pane_tty = pane.get('pane_tty') + pane_id = pane.get("pane_id") + pane_tty = pane.get("pane_tty") - where = window.where({'pane_id': pane_id, 'pane_tty': pane_tty}) + where = window.where({"pane_id": pane_id, "pane_tty": pane_tty}) assert len(where) == 1 assert isinstance(where, list) @@ -135,30 +135,30 @@ def test_get_by_id(server, session): window.split_window() # create second pane for session in server.sessions: - session_id = session.get('session_id') + session_id = session.get("session_id") get_by_id = server.get_by_id(session_id) assert get_by_id == session assert isinstance(get_by_id, Session) - assert server.get_by_id('$' + next(namer)) is None + assert server.get_by_id("$" + next(namer)) is None # session.get_by_id for window in session.windows: - window_id = window.get('window_id') + window_id = window.get("window_id") get_by_id = session.get_by_id(window_id) assert get_by_id == window assert isinstance(get_by_id, Window) - assert session.get_by_id('@' + next(namer)) is None + assert session.get_by_id("@" + next(namer)) is None # window.get_by_id for pane in window.panes: - pane_id = pane.get('pane_id') + pane_id = pane.get("pane_id") get_by_id = window.get_by_id(pane_id) assert get_by_id == pane assert isinstance(get_by_id, Pane) - assert window.get_by_id('%' + next(namer)) is None + assert window.get_by_id("%" + next(namer)) is None diff --git a/tests/test_window.py b/tests/test_window.py index deaf5c67d..a00dafc51 100644 --- a/tests/test_window.py +++ b/tests/test_window.py @@ -17,7 +17,7 @@ def test_select_window(session): window_base_index = int(session.attached_window.index) - window = session.new_window(window_name='testing 3') + window = session.new_window(window_name="testing 3") # self.assertEqual(2, # int(session.attached_window.index)) @@ -26,7 +26,7 @@ def test_select_window(session): session.select_window(window_base_index) assert window_base_index == int(session.attached_window.index) - session.select_window('testing 3') + session.select_window("testing 3") assert int(window_base_index) + 1 == int(session.attached_window.index) assert len(session._windows) == 2 @@ -34,14 +34,14 @@ def test_select_window(session): def test_zfresh_window_data(session): pane_base_index = int( - session.attached_window.show_window_option('pane-base-index', g=True) + session.attached_window.show_window_option("pane-base-index", g=True) ) assert len(session.windows) == 1 assert len(session.attached_window.panes) == 1 current_windows = len(session._windows) - assert session.get('session_id') != '@0' + assert session.get("session_id") != "@0" assert current_windows == 1 assert len(session.attached_window.panes) == 1 @@ -57,24 +57,24 @@ def test_zfresh_window_data(session): assert len(session.attached_window.panes) == 1 window.split_window() session.attached_window.select_pane(pane_base_index) - session.attached_pane.send_keys('cd /srv/www/flaskr') + session.attached_pane.send_keys("cd /srv/www/flaskr") session.attached_window.select_pane(pane_base_index + 1) - session.attached_pane.send_keys('source .venv/bin/activate') - session.new_window(window_name='second') + session.attached_pane.send_keys("source .venv/bin/activate") + session.new_window(window_name="second") current_windows += 1 assert current_windows == len(session._windows) - session.new_window(window_name='hey') + session.new_window(window_name="hey") current_windows += 1 assert current_windows == len(session._windows) session.select_window(1) - session.kill_window(target_window='hey') + session.kill_window(target_window="hey") current_windows -= 1 assert current_windows == len(session._windows) def test_newest_pane_data(session): - window = session.new_window(window_name='test', attach=True) + window = session.new_window(window_name="test", attach=True) assert isinstance(window, Window) assert len(window.panes) == 1 window.split_window(attach=True) @@ -95,7 +95,7 @@ def test_attached_pane(session): def test_split_window(session): """Window.split_window() splits window, returns new Pane, vertical.""" - window_name = 'test split window' + window_name = "test split window" window = session.new_window(window_name=window_name, attach=True) pane = window.split_window() assert len(window.panes) == 2 @@ -105,22 +105,22 @@ def test_split_window(session): def test_split_window_shell(session): """Window.split_window() splits window, returns new Pane, vertical.""" - window_name = 'test split window' - cmd = 'sleep 1m' + window_name = "test split window" + cmd = "sleep 1m" window = session.new_window(window_name=window_name, attach=True) pane = window.split_window(shell=cmd) assert len(window.panes) == 2 assert isinstance(pane, Pane) assert float(window.panes[0].height) <= ((float(window.width) + 1) / 2) - if has_gte_version('3.2'): - assert pane.get('pane_start_command').replace('"', '') == cmd + if has_gte_version("3.2"): + assert pane.get("pane_start_command").replace('"', "") == cmd else: - assert pane.get('pane_start_command') == cmd + assert pane.get("pane_start_command") == cmd def test_split_window_horizontal(session): """Window.split_window() splits window, returns new Pane, horizontal.""" - window_name = 'test split window' + window_name = "test split window" window = session.new_window(window_name=window_name, attach=True) pane = window.split_window(vertical=False) assert len(window.panes) == 2 @@ -130,28 +130,28 @@ def test_split_window_horizontal(session): @pytest.mark.parametrize( "window_name_before,window_name_after", - [('test', 'ha ha ha fjewlkjflwef'), ('test', 'hello \\ wazzup 0')], + [("test", "ha ha ha fjewlkjflwef"), ("test", "hello \\ wazzup 0")], ) def test_window_rename(session, window_name_before, window_name_after): """Window.rename_window().""" - window_name_before = 'test' - window_name_after = 'ha ha ha fjewlkjflwef' + window_name_before = "test" + window_name_after = "ha ha ha fjewlkjflwef" - session.set_option('automatic-rename', 'off') + session.set_option("automatic-rename", "off") window = session.new_window(window_name=window_name_before, attach=True) assert window == session.attached_window - assert window.get('window_name') == window_name_before + assert window.get("window_name") == window_name_before window.rename_window(window_name_after) window = session.attached_window - assert window.get('window_name') == window_name_after + assert window.get("window_name") == window_name_after window = session.attached_window - assert window.get('window_name') == window_name_after + assert window.get("window_name") == window_name_after def test_kill_window(session): @@ -161,16 +161,16 @@ def test_kill_window(session): w = session.attached_window - w.get('window_id') + w.get("window_id") w.kill_window() with pytest.raises(IndexError): - w.get('window_id') + w.get("window_id") def test_show_window_options(session): """Window.show_window_options() returns dict.""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") options = window.show_window_options() assert isinstance(options, dict) @@ -178,95 +178,95 @@ def test_show_window_options(session): def test_set_show_window_options(session): """Set option then Window.show_window_options(key).""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") - window.set_window_option('main-pane-height', 20) - assert window.show_window_options('main-pane-height') == 20 + window.set_window_option("main-pane-height", 20) + assert window.show_window_options("main-pane-height") == 20 - window.set_window_option('main-pane-height', 40) - assert window.show_window_options('main-pane-height') == 40 - assert window.show_window_options()['main-pane-height'] == 40 + window.set_window_option("main-pane-height", 40) + assert window.show_window_options("main-pane-height") == 40 + assert window.show_window_options()["main-pane-height"] == 40 - if has_gte_version('2.3'): - window.set_window_option('pane-border-format', ' #P ') - assert window.show_window_options('pane-border-format') == ' #P ' + if has_gte_version("2.3"): + window.set_window_option("pane-border-format", " #P ") + assert window.show_window_options("pane-border-format") == " #P " def test_empty_window_option_returns_None(session): - window = session.new_window(window_name='test_window') - assert window.show_window_option('alternate-screen') is None + window = session.new_window(window_name="test_window") + assert window.show_window_option("alternate-screen") is None def test_show_window_option(session): """Set option then Window.show_window_option(key).""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") - window.set_window_option('main-pane-height', 20) - assert window.show_window_option('main-pane-height') == 20 + window.set_window_option("main-pane-height", 20) + assert window.show_window_option("main-pane-height") == 20 - window.set_window_option('main-pane-height', 40) - assert window.show_window_option('main-pane-height') == 40 - assert window.show_window_option('main-pane-height') == 40 + window.set_window_option("main-pane-height", 40) + assert window.show_window_option("main-pane-height") == 40 + assert window.show_window_option("main-pane-height") == 40 def test_show_window_option_unknown(session): """Window.show_window_option raises UnknownOption for bad option key.""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") cmd_exception = exc.UnknownOption - if has_gte_version('3.0'): + if has_gte_version("3.0"): cmd_exception = exc.InvalidOption with pytest.raises(cmd_exception): - window.show_window_option('moooz') + window.show_window_option("moooz") def test_show_window_option_ambiguous(session): """show_window_option raises AmbiguousOption for ambiguous option.""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") with pytest.raises(exc.AmbiguousOption): - window.show_window_option('clock-mode') + window.show_window_option("clock-mode") def test_set_window_option_ambiguous(session): """set_window_option raises AmbiguousOption for ambiguous option.""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") with pytest.raises(exc.AmbiguousOption): - window.set_window_option('clock-mode', 12) + window.set_window_option("clock-mode", 12) def test_set_window_option_invalid(session): """Window.set_window_option raises ValueError for invalid option key.""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") - if has_gte_version('2.4'): + if has_gte_version("2.4"): with pytest.raises(exc.InvalidOption): - window.set_window_option('afewewfew', 43) + window.set_window_option("afewewfew", 43) else: with pytest.raises(exc.UnknownOption): - window.set_window_option('afewewfew', 43) + window.set_window_option("afewewfew", 43) def test_move_window(session): """Window.move_window results in changed index""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") new_index = str(int(window.index) + 1) window.move_window(new_index) assert window.index == new_index def test_move_window_to_other_session(server, session): - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") new_session = server.new_session("test_move_window") - window.move_window(session=new_session.get('session_id')) + window.move_window(session=new_session.get("session_id")) assert new_session.get_by_id(window.get("window_id")) == window def test_select_layout_accepts_no_arg(server, session): """tmux allows select-layout with no arguments, so let's allow it here.""" - window = session.new_window(window_name='test_window') + window = session.new_window(window_name="test_window") window.select_layout()