Skip to content
Open
19 changes: 19 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 22 additions & 4 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
24 changes: 23 additions & 1 deletion docs/topics/automation_patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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; "
Expand Down Expand Up @@ -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 [
Expand Down Expand Up @@ -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; "
Expand Down Expand Up @@ -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}; "
Expand Down Expand Up @@ -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; "
Expand Down Expand Up @@ -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; "
Expand Down
18 changes: 18 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"

Expand All @@ -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 = [
Expand Down
5 changes: 5 additions & 0 deletions src/libtmux/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
54 changes: 39 additions & 15 deletions src/libtmux/pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -81,42 +80,67 @@ 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`.
"""
c = user_path / ".tmux.conf"
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(
Expand Down
4 changes: 4 additions & 0 deletions src/libtmux/test/retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down
4 changes: 4 additions & 0 deletions tests/legacy_api/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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"
Expand All @@ -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")
Expand Down
1 change: 1 addition & 0 deletions tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 7 additions & 1 deletion tests/test_pane.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
Loading
Loading