diff --git a/CHANGES b/CHANGES index fe2afd8e12..aa372516c0 100644 --- a/CHANGES +++ b/CHANGES @@ -13,6 +13,25 @@ _Notes on the upcoming release will go here._ Local watch mode, the editor and CI use ty 0.0.113. CI checks the minimum supported Python version and its matrix target. ([#936](https://github.com/tmux-python/libtmux/pull/936)) +### What's new + +#### pytest plugin: deterministic shell in test fixtures (#662) + +The bundled `.tmux.conf` fixture now pins `default-shell` to `/bin/sh` +and the plugin force-aligns `$SHELL=/bin/sh` for every test. Skips +developer-shell init per pane and eliminates the prompt-rendering +noise that used to flake `capture-pane` and `automatic-rename` +assertions in downstream consumers. Workspaces can still override +`default-shell` per-session because `default-command` is intentionally +left empty. + +#### `get_version()` is now cached per tmux binary (#662) + +Repeat calls within a process — plugin construction, version checks +during pane capture, CLI startup — reuse the parsed version instead +of re-running `tmux -V`. `get_version.cache_clear()` is exposed for +test fixtures that swap the tmux binary. + ## libtmux 0.70.0 (2026-11-28) libtmux 0.70.0 moves static type checking from mypy to strict diff --git a/conftest.py b/conftest.py index a98a3b77e7..dc54a9d0a6 100644 --- a/conftest.py +++ b/conftest.py @@ -19,9 +19,9 @@ from libtmux._internal.control_mode import ControlMode from libtmux.client import Client +from libtmux.common import get_version from libtmux.formats import Format from libtmux.pane import Pane -from libtmux.pytest_plugin import USING_ZSH from libtmux.server import Server from libtmux.session import Session from libtmux.window import Window @@ -81,11 +81,29 @@ def setup_fn( """Function-level test configuration fixtures for pytest.""" +@pytest.fixture(autouse=True) +def _reset_get_version_cache() -> t.Generator[None, None, None]: + """Clear ``libtmux.common.get_version`` lru_cache around every test. + + ``get_version`` is memoized per ``tmux_bin`` so production code only + forks ``tmux -V`` once per process. Tests that monkeypatch + ``tmux_cmd`` to return synthetic versions, or that exercise the real + binary, otherwise leak cached values across tests and produce + order-dependent failures. + """ + yield + get_version.cache_clear() + + @pytest.fixture(autouse=True, scope="session") def setup_session( request: pytest.FixtureRequest, config_file: pathlib.Path, ) -> None: - """Session-level test configuration for pytest.""" - if USING_ZSH: - request.getfixturevalue("zshrc") + """Session-level test configuration for pytest. + + Requesting ``config_file`` here forces the ``.tmux.conf`` fixture + to be materialized once per session even when no test requests + it directly. + """ + del request, config_file diff --git a/docs/topics/automation_patterns.md b/docs/topics/automation_patterns.md index 43554096a0..9b421073a2 100644 --- a/docs/topics/automation_patterns.md +++ b/docs/topics/automation_patterns.md @@ -85,6 +85,9 @@ Capture the pane and read the most recent state after each explicit signal. >>> status_window = session.new_window(window_name='status-check', attach=False) >>> status_pane = status_window.active_pane +>>> status_pane.send_keys('tmux wait-for -S status-shell-ready') +>>> server.wait_for('status-shell-ready') + >>> def latest_status(pane): ... """Return the most recent status line.""" ... statuses = [ @@ -138,6 +141,9 @@ command a distinct channel name. >>> monitor_window = session.new_window(window_name='monitor', attach=False) >>> monitor_pane = monitor_window.active_pane +>>> monitor_pane.send_keys('tmux wait-for -S monitor-shell-ready') +>>> server.wait_for('monitor-shell-ready') + >>> completion_channel = 'libtmux-automation-ready' >>> monitor_pane.send_keys( ... "sleep 0.2; printf 'command %s\\n' complete; " @@ -182,6 +188,9 @@ pane between commands when each verdict has to stand on its own. >>> error_window = session.new_window(window_name='error-check', attach=False) >>> error_pane = error_window.active_pane +>>> error_pane.send_keys('tmux wait-for -S error-shell-ready') +>>> server.wait_for('error-shell-ready') + >>> def command_output(pane, tag='out:'): ... """The lines the command tagged as its own.""" ... return [ @@ -238,6 +247,9 @@ cannot be mistaken for output. >>> capture_window = session.new_window(window_name='capture', attach=False) >>> capture_pane = capture_window.active_pane +>>> capture_pane.send_keys('tmux wait-for -S capture-shell-ready') +>>> server.wait_for('capture-shell-ready') + >>> capture_channel = 'libtmux-automation-capture' >>> capture_pane.send_keys( ... "printf 'result%s%s\\n' : alpha : beta; " @@ -277,13 +289,18 @@ Window(@... ...) >>> pane2 = pane1.split(direction=PaneDirection.Right) >>> pane3 = pane1.split(direction=PaneDirection.Below) ->>> # Start tasks in parallel >>> tasks = [ ... (pane1, '0.2', '1', 'libtmux-parallel-1'), ... (pane2, '0.1', '2', 'libtmux-parallel-2'), ... (pane3, '0.3', '3', 'libtmux-parallel-3'), ... ] +>>> for pane, _, number, _ in tasks: +... pane.send_keys(f'tmux wait-for -S parallel-shell-{number}') +>>> for _, _, number, _ in tasks: +... server.wait_for(f'parallel-shell-{number}') + +>>> # Start tasks in parallel >>> for pane, delay, number, channel in tasks: ... pane.send_keys( ... f"sleep {delay}; printf 'Task %s\\n' {number}; " @@ -386,6 +403,8 @@ never outlives its purpose. ```python >>> with session.new_window(window_name='subtask') as sub_window: ... pane = sub_window.active_pane +... pane.send_keys('tmux wait-for -S subtask-shell-ready') +... server.wait_for('subtask-shell-ready') ... subtask_channel = 'libtmux-subtask-complete' ... pane.send_keys( ... "printf 'Subtask %s\\n' running; " @@ -647,6 +666,9 @@ performed rather than text it merely echoed. >>> bp_window = session.new_window(window_name='best-practice', attach=False) >>> bp_pane = bp_window.active_pane +>>> bp_pane.send_keys('tmux wait-for -S bp-shell-ready') +>>> server.wait_for('bp-shell-ready') + >>> bp_channel = 'libtmux-best-practice-complete' >>> bp_pane.send_keys( ... "printf 'work %s\\n' complete; " diff --git a/pyproject.toml b/pyproject.toml index e5f9b2dc15..1cb9ffb67b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -229,6 +229,8 @@ extend-select = [ "PTH", # flake8-simplify — https://docs.astral.sh/ruff/rules/#flake8-simplify-sim "SIM", + # flake8-tidy-imports — https://docs.astral.sh/ruff/rules/#flake8-tidy-imports-tid + "TID", # tryceratops — https://docs.astral.sh/ruff/rules/#tryceratops-try "TRY", # Perflint — https://docs.astral.sh/ruff/rules/#perflint-perf @@ -268,6 +270,15 @@ builtins-allowed-modules = [ "types", ] +[tool.ruff.lint.flake8-tidy-imports.banned-api] +# ``time.sleep`` is banned in tests because it masks non-determinism +# rather than proving a condition. Tests should use +# ``libtmux.test.retry.retry_until`` (or ``pane.wait_for_text`` in +# pane-driven cases) to poll until the desired state is observed. +# Production retry/interval helpers that legitimately sleep are +# exempted via ``per-file-ignores`` below. +"time.sleep".msg = "Avoid time.sleep — use libtmux.test.retry.retry_until or pane.wait_for_text. Production retry/interval code is exempted via per-file-ignores." + [tool.ruff.lint.pydocstyle] convention = "numpy" @@ -292,6 +303,13 @@ convention = "numpy" # `Server.is_alive` maps any unreachable-daemon failure to False — https://docs.astral.sh/ruff/rules/blind-except/ "BLE001", ] +# retry.py implements the retry/poll-with-sleep helper itself; it is +# the *replacement* for time.sleep in tests, so the rule does not +# apply to its own implementation. tests/test/test_retry.py exercises +# that helper's timing behavior, which intentionally sleeps to +# simulate slow operations. +"src/libtmux/test/retry.py" = ["TID251"] +"tests/test/test_retry.py" = ["TID251"] [tool.pytest.ini_options] addopts = [ diff --git a/src/libtmux/common.py b/src/libtmux/common.py index cee78502d2..c1c696f0fa 100644 --- a/src/libtmux/common.py +++ b/src/libtmux/common.py @@ -709,6 +709,11 @@ def get_version(tmux_bin: str | None = None) -> LooseVersion: If using OpenBSD's base system tmux, the version will have ``-openbsd`` appended to the latest version, e.g. ``2.4-openbsd``. + The version is memoized per ``tmux_bin`` value: ``tmux -V`` runs once per + distinct binary path within a process. Use ``get_version.cache_clear()`` + when test fixtures swap the tmux binary or stub :func:`tmux_cmd`. Errors + are not cached, so a transient failure does not poison the lookup. + Parameters ---------- tmux_bin : str, optional diff --git a/src/libtmux/pytest_plugin.py b/src/libtmux/pytest_plugin.py index f9cdf0a670..fa580ffa38 100644 --- a/src/libtmux/pytest_plugin.py +++ b/src/libtmux/pytest_plugin.py @@ -23,7 +23,6 @@ from libtmux.session import Session logger = logging.getLogger(__name__) -USING_ZSH = "zsh" in os.getenv("SHELL", "") def _reap_test_server(socket_name: str | None) -> None: @@ -81,24 +80,26 @@ def user_path(home_path: pathlib.Path, home_user_name: str) -> pathlib.Path: return p -@pytest.fixture(scope="session") -def zshrc(user_path: pathlib.Path) -> pathlib.Path: - """Suppress ZSH default message. - - Needs a startup file .zshenv, .zprofile, .zshrc, .zlogin. - """ - p = user_path / ".zshrc" - p.touch() - return p - - @pytest.fixture(scope="session") def config_file(user_path: pathlib.Path) -> pathlib.Path: """Return fixture for ``.tmux.conf`` configuration. - - ``base-index -g 1`` - - These guarantee pane and windows targets can be reliably referenced and asserted. + Pinned settings: + + - ``base-index 1`` — guarantees pane and window targets can be + reliably referenced and asserted starting at 1. + - ``default-shell /bin/sh`` — bypasses the developer's interactive + shell (zsh/bash) so each test pane skips ~60ms of shell init + and the non-deterministic prompt rendering that otherwise causes + flakes against ``automatic-rename`` and ``capture-pane`` assertions. + ``default-command`` is intentionally left at tmux's default + (empty string) so that consumer test workspaces — for example + tmuxp's ``window_options_after.yaml`` which pins + ``default-shell: /bin/bash`` to test Up-arrow shell history — + can override ``default-shell`` per-session and have it take + effect. Setting ``default-command`` here would short-circuit + that override path (per tmux's ``cmd-new-window.c``, + ``default-command`` always wins over ``default-shell``). Note: You will need to set the home directory, see :ref:`set_home`. """ @@ -106,17 +107,40 @@ def config_file(user_path: pathlib.Path) -> pathlib.Path: c.write_text( """ set -g base-index 1 +set -g default-shell /bin/sh """, encoding="utf-8", ) return c +@pytest.fixture(autouse=True) +def _pin_test_shell_env(monkeypatch: pytest.MonkeyPatch) -> None: + """Force ``$SHELL`` to ``/bin/sh`` for every test that loads this plugin. + + The companion ``config_file`` fixture pins tmux's ``default-shell`` to + ``/bin/sh``; this autouse hook keeps Python-side ``os.getenv("SHELL")`` + consumers aligned. Without it, libtmux's conftest already covers its + own tests via ``clear_env``, but external consumers (notably tmuxp's + ``test_automatic_rename_option`` which asserts + ``w.name in {Path(os.getenv("SHELL")).name, ...}``) see the + developer's interactive shell on the env side and ``/bin/sh`` on the + tmux side and flake on the mismatch. Running autouse from the plugin + ensures every consumer's tests get the alignment for free. + """ + monkeypatch.setenv("SHELL", "/bin/sh") + + @pytest.fixture def clear_env(monkeypatch: pytest.MonkeyPatch) -> None: """Clear out any unnecessary environment variables that could interrupt tests. tmux show-environment tests were being interrupted due to a lot of crazy env vars. + + Note: ``SHELL`` alignment with tmux's ``default-shell`` is handled by + the ``_pin_test_shell_env`` autouse fixture in this same module, so + callers do not need to opt into ``clear_env`` solely to get that + behavior. """ for k in os.environ: if not any( diff --git a/src/libtmux/test/retry.py b/src/libtmux/test/retry.py index 30dc06b320..6d5d0afe4a 100644 --- a/src/libtmux/test/retry.py +++ b/src/libtmux/test/retry.py @@ -90,6 +90,10 @@ def retry_until( >>> window = session.new_window(window_name='retry_until_args') >>> panes = [window.active_pane, window.split()] + >>> for i, pane in enumerate(panes): + ... pane.send_keys(f'tmux wait-for -S retry-shell-{i}') + >>> for i in range(len(panes)): + ... server.wait_for(f'retry-shell-{i}') >>> for pane in panes: ... pane.send_keys('echo ready') diff --git a/tests/legacy_api/test_common.py b/tests/legacy_api/test_common.py index 8fd1ef54d1..992cec934c 100644 --- a/tests/legacy_api/test_common.py +++ b/tests/legacy_api/test_common.py @@ -49,6 +49,7 @@ def mock_tmux_cmd(*args: CmdArg, tmux_bin: str | None = None) -> Hi: return Hi() monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) + get_version.cache_clear() assert has_minimum_version() assert has_gte_version(TMUX_MIN_VERSION) @@ -70,6 +71,7 @@ def mock_tmux_cmd(*args: CmdArg, tmux_bin: str | None = None) -> Hi: return Hi() monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) + get_version.cache_clear() assert has_minimum_version() assert has_gte_version(TMUX_MIN_VERSION) @@ -88,6 +90,7 @@ def mock_tmux_cmd(*args: CmdArg, tmux_bin: str | None = None) -> Hi: monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) monkeypatch.setattr(sys, "platform", "openbsd 5.2") + get_version.cache_clear() assert has_minimum_version() assert has_gte_version(TMUX_MIN_VERSION) assert has_gt_version(TMUX_MAX_VERSION), "Greater than the max-supported version" @@ -106,6 +109,7 @@ def mock_tmux_cmd(*args: CmdArg, tmux_bin: str | None = None) -> Hi: return Hi() monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) + get_version.cache_clear() with pytest.raises(exc.LibTmuxException) as exc_info: get_version() exc_info.match("does not meet the minimum tmux version requirement") diff --git a/tests/test_common.py b/tests/test_common.py index 5c03858b6e..12961a1494 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -1042,6 +1042,7 @@ def mock_tmux_cmd(*args: CmdArg, tmux_bin: str | None = None) -> MockTmuxOutput: monkeypatch.setattr(libtmux.common, "tmux_cmd", mock_tmux_cmd) if mock_platform is not None: monkeypatch.setattr(sys, "platform", mock_platform) + get_version.cache_clear() if raises: with pytest.raises(exc.LibTmuxException) as exc_info: diff --git a/tests/test_pane.py b/tests/test_pane.py index e4b484e8b7..f0f64c3e0f 100644 --- a/tests/test_pane.py +++ b/tests/test_pane.py @@ -1468,7 +1468,13 @@ def test_break_pane_no_name_uses_natural_name(session: Session) -> None: pane = window.active_pane assert pane is not None - new_pane = pane.split(shell="sleep 123") + new_pane = pane.split(shell="exec sleep 123") + + def command_started() -> bool: + new_pane.refresh() + return new_pane.pane_current_command == "sleep" + + retry_until(command_started) broken = new_pane.break_pane() assert broken.window_name == "sleep" diff --git a/tests/test_pytest_plugin.py b/tests/test_pytest_plugin.py index 23acbcfe92..c5e578d6d9 100644 --- a/tests/test_pytest_plugin.py +++ b/tests/test_pytest_plugin.py @@ -6,11 +6,11 @@ import os import pathlib import textwrap -import time import typing as t from libtmux.pytest_plugin import _reap_test_server from libtmux.server import Server +from libtmux.test.retry import retry_until if t.TYPE_CHECKING: import pytest @@ -101,6 +101,38 @@ def test_test_server(TestServer: t.Callable[..., Server]) -> None: assert server2.socket_name != server.socket_name +def test_pin_test_shell_env_aligns_shell_with_default_shell() -> None: + """The autouse plugin fixture pins ``$SHELL`` to ``/bin/sh``. + + Code that compares ``os.getenv("SHELL")`` against the tmux pane's + running command (notably tmuxp's ``test_automatic_rename_option``) + must see ``/bin/sh`` to match the ``default-shell`` pinned in + :func:`config_file`. Because the alignment fixture is autouse from + the libtmux pytest plugin, every test that loads the plugin — + including external consumers — gets the alignment without explicit + fixture opt-in. + """ + assert os.environ.get("SHELL") == "/bin/sh" + + +def test_config_file_pins_minimal_test_shell(config_file: pathlib.Path) -> None: + """The shipped ``.tmux.conf`` pins ``/bin/sh`` as the default shell. + + Forcing ``default-shell`` to ``/bin/sh`` skips the developer's + interactive shell init (~60ms per pane for zsh) and eliminates the + non-deterministic prompt rendering that flakes ``capture-pane`` and + ``automatic-rename`` assertions. The ``base-index 1`` line is + behavioral and must remain. ``default-command`` is intentionally + NOT set so consumer test workspaces can override ``default-shell`` + per-session (per tmux's ``cmd-new-window.c``, ``default-command`` + always wins, which would short-circuit those overrides). + """ + content = config_file.read_text() + assert "set -g base-index 1" in content + assert "set -g default-shell /bin/sh" in content + assert "set -g default-command" not in content + + def test_test_server_with_config( TestServer: t.Callable[..., Server], tmp_path: pathlib.Path, @@ -130,9 +162,13 @@ def test_test_server_cleanup(TestServer: t.Callable[..., Server]) -> None: # Verify server is alive assert server.is_alive() is True - # Delete server and verify cleanup + # Delete server and verify cleanup. Poll the socket until tmux's + # async unlink completes, replacing a flaky time.sleep(0.1). server.kill() - time.sleep(0.1) # Give time for cleanup + assert retry_until( + lambda: not server.is_alive(), + seconds=2, + ) # Create new server to verify old one was cleaned up new_server = TestServer() diff --git a/tests/test_server.py b/tests/test_server.py index fe2f462cba..a627a165cb 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -587,7 +587,6 @@ def test_new_session_shell_env(server: Server) -> None: window_command=cmd, environment=env, ) - time.sleep(0.1) window = mysession.windows[0] pane = window.panes[0] assert mysession.session_name == "test_new_session_env" @@ -2778,7 +2777,7 @@ def test_server_timeout_exempts_ordinary_and_lock_waits_but_bounds_signals( bounded = Server(socket_name=server.socket_name, timeout=0.2) def _delayed_signal() -> None: - time.sleep(0.35) + time.sleep(0.35) # noqa: TID251 - must outlive Server(timeout=0.2) server.wait_for("slow-signal", set_flag=True) signaller = threading.Thread(target=_delayed_signal) @@ -2791,7 +2790,7 @@ def _delayed_signal() -> None: server.wait_for("held-lock", lock=True) def _delayed_unlock() -> None: - time.sleep(0.35) + time.sleep(0.35) # noqa: TID251 - must outlive Server(timeout=0.2) server.wait_for("held-lock", unlock=True) unlocker = threading.Thread(target=_delayed_unlock) @@ -2872,7 +2871,7 @@ def test_per_call_timeout_none_overrides_server_timeout(server: Server) -> None: bounded.cmd("wait-for", "override-never") def _delayed_signal() -> None: - time.sleep(0.35) + time.sleep(0.35) # noqa: TID251 - must outlive Server(timeout=0.2) server.wait_for("override-ch", set_flag=True) signaller = threading.Thread(target=_delayed_signal)