From 5a58f7f86d7a30269031c19e4b04f40c51d3e916 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Tue, 28 Apr 2026 18:07:23 -0500 Subject: [PATCH 1/8] perf(test[shell]) pin tmux default-shell to /bin/sh in test config MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: Profiling tmuxp's test suite showed 80% of the ~62s wall time was shell/fixture overhead, not tmux commands. The dominant cost was every tmux pane spawning the developer's $SHELL — typically /bin/zsh — which costs ~60ms of init per pane (cold ~400ms) and produces non-deterministic prompt output that flakes capture-pane assertions. A/B confirmed SHELL=/bin/sh cuts the full tmuxp suite from ~70s to ~32s (2.2x faster) and eliminates a flaky test. what: - pytest_plugin.config_file: add `set -g default-shell /bin/sh` to the shipped .tmux.conf. Per tmux's cmd-new-window.c, default-shell takes effect when default-command is empty (the default), so consumer test workspaces can still override default-shell per-session — for example tmuxp's window_options_after.yaml pins default-shell: /bin/bash to test Up-arrow shell history. Setting default-command here would short-circuit those overrides, so it is intentionally left at tmux's default - tests/test_pytest_plugin.py: add a regression test asserting that base-index 1 and default-shell /bin/sh appear in the generated config, and that default-command is intentionally absent --- src/libtmux/pytest_plugin.py | 20 +++++++++++++++++--- tests/test_pytest_plugin.py | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/libtmux/pytest_plugin.py b/src/libtmux/pytest_plugin.py index f9cdf0a670..6bfa8345d6 100644 --- a/src/libtmux/pytest_plugin.py +++ b/src/libtmux/pytest_plugin.py @@ -96,9 +96,22 @@ def zshrc(user_path: pathlib.Path) -> pathlib.Path: 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,6 +119,7 @@ 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", ) diff --git a/tests/test_pytest_plugin.py b/tests/test_pytest_plugin.py index 23acbcfe92..d363d6a07d 100644 --- a/tests/test_pytest_plugin.py +++ b/tests/test_pytest_plugin.py @@ -101,6 +101,24 @@ def test_test_server(TestServer: t.Callable[..., Server]) -> None: assert server2.socket_name != server.socket_name +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, From 64eb2b03b43e08dce172ebb61e297b39954586e5 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Tue, 28 Apr 2026 18:09:55 -0500 Subject: [PATCH 2/8] perf(test[shell]) autouse-pin $SHELL to /bin/sh in pytest plugin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: Commit 1 forced tmux's default-shell to /bin/sh in the test config_file fixture, but $SHELL on the developer's machine still reports /bin/zsh. Tests that compare os.getenv("SHELL") against the tmux pane's running command — notably tmuxp's test_automatic_rename_option which asserts `w.name in {pathlib.Path(os.getenv("SHELL")).name, ...}` — flake because the pane runs sh while $SHELL says zsh. A clear_env-only fix would not propagate to consumers like tmuxp whose conftest does not consume libtmux's clear_env fixture. Pinning $SHELL via an autouse fixture in the libtmux pytest plugin itself ensures every plugin consumer's tests get the alignment without explicit opt-in. what: - pytest_plugin._pin_test_shell_env: new autouse function-scoped fixture that runs `monkeypatch.setenv("SHELL", "/bin/sh")` before every test. monkeypatch restores the prior value at teardown so no global state leaks between processes - pytest_plugin.clear_env: docstring updated to point at the new autouse fixture; the SHELL handling moved out of clear_env so callers do not need to opt into clear_env solely to get the alignment - tests/test_pytest_plugin.py: regression test asserting os.environ["SHELL"] == "/bin/sh" inside a test body, with no explicit fixture opt-in (proves the autouse path) --- src/libtmux/pytest_plugin.py | 22 ++++++++++++++++++++++ tests/test_pytest_plugin.py | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/libtmux/pytest_plugin.py b/src/libtmux/pytest_plugin.py index 6bfa8345d6..be2bbea849 100644 --- a/src/libtmux/pytest_plugin.py +++ b/src/libtmux/pytest_plugin.py @@ -126,11 +126,33 @@ def config_file(user_path: pathlib.Path) -> pathlib.Path: 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/tests/test_pytest_plugin.py b/tests/test_pytest_plugin.py index d363d6a07d..7ad75eaa27 100644 --- a/tests/test_pytest_plugin.py +++ b/tests/test_pytest_plugin.py @@ -101,6 +101,20 @@ 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. From 88deec8c34980b00620077de55d344bab31fa090 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Tue, 28 Apr 2026 18:21:58 -0500 Subject: [PATCH 3/8] chore(test[zsh]) retire USING_ZSH plumbing in libtmux MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: With commit 1 hardcoding default-shell /bin/sh in the test config and commit 2 forcing $SHELL=/bin/sh autouse, the entire USING_ZSH apparatus is dead code. The zshrc fixture exists solely to suppress zsh's first-run greeting that interfered with output capture — the new config bypasses zsh entirely so the greeting never fires. what: - pytest_plugin.py: drop the module-level USING_ZSH constant and the zshrc fixture (with its skipif decorator) - conftest.py: drop the USING_ZSH import and the conditional `if USING_ZSH: request.getfixturevalue("zshrc")` from setup_session. Keep config_file as a setup_session arg so the .tmux.conf fixture still materializes once per session (now with an explanatory docstring) --- conftest.py | 11 +++++++---- src/libtmux/pytest_plugin.py | 12 ------------ 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/conftest.py b/conftest.py index a98a3b77e7..e371c5206a 100644 --- a/conftest.py +++ b/conftest.py @@ -21,7 +21,6 @@ from libtmux.client import Client 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 @@ -86,6 +85,10 @@ 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/src/libtmux/pytest_plugin.py b/src/libtmux/pytest_plugin.py index be2bbea849..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,17 +80,6 @@ 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. From 2726a67d1944db6f81949552350b3a0f01786004 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Tue, 28 Apr 2026 18:17:14 -0500 Subject: [PATCH 4/8] test(retry) replace speculative time.sleep calls with retry_until polls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: Three test sites used time.sleep to mask non-determinism that should be deterministic. With default-shell /bin/sh (commit 1) the zsh-prompt timing race that motivated some of these is gone, and libtmux ships retry_until in src/libtmux/test/retry.py for exactly this purpose. Sleeps mask flakiness while retry_until proves the condition; the latter is strictly better. what: - tests/test_server.py:test_new_session_shell_env: drop time.sleep(0.1) after new_session. The subsequent assertions (session_name, pane_start_command) read static properties populated synchronously by new_session — there's no race to mask. ruff auto-removed the now unused `import time` - tests/test_window.py:test_split_with_environment: replace time.sleep(0.05) with retry_until polling pane.capture_pane()[-2] for each expected env var output. retry_until's default 0.05s interval matches the original sleep but bounds the wait at 2s deterministic vs an arbitrary fixed delay. The pane uses a custom shell (env PS1='$ ' sh) so the global default-shell pin doesn't apply - tests/test_pytest_plugin.py:test_test_server_cleanup: replace time.sleep(0.1) "give time for cleanup" with retry_until polling server.is_alive() returning False. tmux's socket unlink is async; the poll catches it deterministically vs hoping 0.1s is enough --- tests/test_pytest_plugin.py | 10 +++++++--- tests/test_server.py | 1 - 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/test_pytest_plugin.py b/tests/test_pytest_plugin.py index 7ad75eaa27..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 @@ -162,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..8ce02edd1c 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" From 28d074fc824d9ceef35cb536f72f9f00a3906110 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Tue, 28 Apr 2026 18:19:44 -0500 Subject: [PATCH 5/8] chore(lint[ruff]) ban time.sleep in tests via flake8-tidy-imports TID251 why: Commits 1-3 eliminated speculative time.sleep usage from the test suite; without a guardrail, new contributors will reintroduce sleeps to mask shell or fixture timing instead of using retry_until. Confirmed via ruff's banned_api.rs source (crates/ruff_linter/src/rules/ flake8_tidy_imports/rules/banned_api.rs:59 banned_attribute_access) that TID251 catches both `import time; time.sleep()` call sites and `from time import sleep` imports. The TID251.py test fixture proves the attribute-access path triggers exactly like our case. what: - pyproject.toml [tool.ruff.lint] select: add `TID` to enable flake8-tidy-imports rules - [tool.ruff.lint.flake8-tidy-imports.banned-api]: ban "time.sleep" with a message pointing contributors at libtmux.test.retry.retry_until and pane.wait_for_text as deterministic alternatives - [tool.ruff.lint.per-file-ignores]: - src/libtmux/test/retry.py exempted because it implements the helper - tests/test/test_retry.py exempted because it tests the helper's timing behavior and intentionally simulates slow operations --- pyproject.toml | 18 ++++++++++++++++++ tests/test_server.py | 6 +++--- 2 files changed, 21 insertions(+), 3 deletions(-) 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/tests/test_server.py b/tests/test_server.py index 8ce02edd1c..a627a165cb 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -2777,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) @@ -2790,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) @@ -2871,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) From 0c51afed9157c9a6da0bcd1a20c7335d6fe95f1d Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Tue, 28 Apr 2026 17:54:48 -0500 Subject: [PATCH 6/8] perf(common[get_version]) memoize tmux -V probe per binary path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: get_version() shells out to "tmux -V" via tmux_cmd. Plugin construction, has_gte_version() checks in capture_pane, and CLI startup all call it repeatedly within a single process. Profiling tmuxp's full test suite showed ~108 redundant fork+exec invocations of "tmux -V" per run — eliminating these trims real wall time on test suites and on production CLIs that resolve the version multiple times. what: - common.get_version: wrap with functools.lru_cache(maxsize=8) keyed by tmux_bin so repeat calls reuse the parsed LooseVersion. Errors are not cached; cache_clear() exposed for fixture resets - conftest.py: autouse fixture clears the cache around every test so monkeypatched tmux_cmd doublings in tests/test_common.py and tests/legacy_api/test_common.py do not leak synthetic versions into later tests - tests/test_common.py: add explicit regression test for the cache hit count and cache_clear() semantics; add cache_clear() before monkeypatched mocks so the fixture's pre-test state is irrelevant - tests/legacy_api/test_common.py: same defensive cache_clear() before each tmux_cmd-mocking test --- conftest.py | 15 +++++++++++++++ src/libtmux/common.py | 5 +++++ tests/legacy_api/test_common.py | 4 ++++ tests/test_common.py | 1 + 4 files changed, 25 insertions(+) diff --git a/conftest.py b/conftest.py index e371c5206a..dc54a9d0a6 100644 --- a/conftest.py +++ b/conftest.py @@ -19,6 +19,7 @@ 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.server import Server @@ -80,6 +81,20 @@ 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, 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/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: From 31dfd9da8a5d1f7c4bc92a4ac4c87d96509cea6f Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 29 Nov 2026 19:39:06 -0600 Subject: [PATCH 7/8] test(shell): Fix /bin/sh races in pane and docs why: Pinning default-shell to /bin/sh uses dash on Ubuntu, where sh -c keeps sh as pane_current_command without exec and cooked-pty echo races initial prompt output when send_keys runs before shell readiness. what: - Use exec sleep 123 and retry_until in test_break_pane_no_name_uses_natural_name - Add tmux wait-for shell-readiness barriers to remaining automation_patterns.md and retry_until doctests --- docs/topics/automation_patterns.md | 24 +++++++++++++++++++++++- src/libtmux/test/retry.py | 4 ++++ tests/test_pane.py | 8 +++++++- 3 files changed, 34 insertions(+), 2 deletions(-) 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/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/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" From 78d1f245851ac846c98dfe3df7fd04b83802bc35 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Tue, 28 Apr 2026 20:04:26 -0500 Subject: [PATCH 8/8] docs(CHANGES) Shell-pinned test fixtures and cached get_version --- CHANGES | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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