Debian Codegraph @

src/libtmux/pytest_plugin.py

raw symbols SCIP
1 """libtmux pytest plugin."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import functools
7 import getpass
8 import logging
9 import os
10 import pathlib
11 import typing as t
12
13 import pytest
14
15 from libtmux import exc
16 from libtmux._internal.control_mode import ControlMode
17 from libtmux.server import Server
18 from libtmux.test.constants import TEST_SESSION_PREFIX
19 from libtmux.test.random import get_test_session_name, namer
20
21 if t.TYPE_CHECKING:
22 from libtmux.session import Session
23
24 logger = logging.getLogger(__name__)
25 USING_ZSH = "zsh" in os.getenv("SHELL", "")
26
27
28 def _reap_test_server(socket_name: str | None) -> None:
29 """Kill the tmux daemon on ``socket_name`` and unlink the socket file.
30
31 Invoked from the :func:`server` and :func:`TestServer` fixture
32 finalizers to guarantee teardown even when the daemon has already
33 exited (``kill`` is a no-op then) and the socket file was left on
34 disk. tmux does not reliably ``unlink(2)`` its socket on
35 non-graceful exit, so ``/tmp/tmux-<uid>/`` otherwise accumulates
36 stale entries across test runs.
37
38 Conservative: suppresses ``LibTmuxException`` / ``OSError`` on both
39 the kill and the unlink. A finalizer that raises replaces the real
40 test failure with a cleanup error, and cleanup failures are not
41 actionable (socket already gone, permissions changed, race with a
42 concurrent pytest-xdist worker).
43 """
44 if not socket_name:
45 return
46
47 with contextlib.suppress(exc.LibTmuxException, OSError):
48 srv = Server(socket_name=socket_name)
49 if srv.is_alive():
50 srv.kill()
51
52 # ``Server(socket_name=...)`` does not populate ``socket_path`` —
53 # the Server class only derives the path when neither ``socket_name``
54 # nor ``socket_path`` was supplied. Recompute the location tmux uses
55 # so we can unlink the file regardless of daemon state.
56 tmux_tmpdir = pathlib.Path(os.environ.get("TMUX_TMPDIR", "/tmp"))
57 socket_path = tmux_tmpdir / f"tmux-{os.geteuid()}" / socket_name
58 with contextlib.suppress(OSError):
59 socket_path.unlink(missing_ok=True)
60
61
62 @pytest.fixture(scope="session")
63 def home_path(tmp_path_factory: pytest.TempPathFactory) -> pathlib.Path:
64 """Temporary `/home/` path."""
65 return tmp_path_factory.mktemp("home")
66
67
68 @pytest.fixture(scope="session")
69 def home_user_name() -> str:
70 """Return default username to set for :fixture:`user_path` fixture."""
71 return getpass.getuser()
72
73
74 @pytest.fixture(scope="session")
75 def user_path(home_path: pathlib.Path, home_user_name: str) -> pathlib.Path:
76 """Ensure and return temporary user directory.
77
78 Note: You will need to set the home directory, see :ref:`set_home`.
79 """
80 p = home_path / home_user_name
81 p.mkdir()
82 return p
83
84
85 @pytest.fixture(scope="session")
86 def zshrc(user_path: pathlib.Path) -> pathlib.Path:
87 """Suppress ZSH default message.
88
89 Needs a startup file .zshenv, .zprofile, .zshrc, .zlogin.
90 """
91 p = user_path / ".zshrc"
92 p.touch()
93 return p
94
95
96 @pytest.fixture(scope="session")
97 def config_file(user_path: pathlib.Path) -> pathlib.Path:
98 """Return fixture for ``.tmux.conf`` configuration.
99
100 - ``base-index -g 1``
101
102 These guarantee pane and windows targets can be reliably referenced and asserted.
103
104 Note: You will need to set the home directory, see :ref:`set_home`.
105 """
106 c = user_path / ".tmux.conf"
107 c.write_text(
108 """
109 set -g base-index 1
110 """,
111 encoding="utf-8",
112 )
113 return c
114
115
116 @pytest.fixture
117 def clear_env(monkeypatch: pytest.MonkeyPatch) -> None:
118 """Clear out any unnecessary environment variables that could interrupt tests.
119
120 tmux show-environment tests were being interrupted due to a lot of crazy env vars.
121 """
122 for k in os.environ:
123 if not any(
124 needle in k.lower()
125 for needle in [
126 "window",
127 "tmux",
128 "pane",
129 "session",
130 "pytest",
131 "path",
132 "pwd",
133 "shell",
134 "home",
135 "xdg",
136 "disable_auto_title",
137 "lang",
138 "term",
139 ]
140 ):
141 monkeypatch.delenv(k)
142
143
144 @pytest.fixture
145 def server(
146 request: pytest.FixtureRequest,
147 monkeypatch: pytest.MonkeyPatch,
148 config_file: pathlib.Path,
149 ) -> Server:
150 """Return new, temporary :class:`libtmux.Server`.
151
152 >>> from libtmux.server import Server
153
154 >>> def test_example(server: Server) -> None:
155 ... assert isinstance(server, Server)
156 ... session = server.new_session('my session')
157 ... assert len(server.sessions) == 1
158 ... assert [session.name.startswith('my') for session in server.sessions]
159
160 .. ::
161 >>> locals().keys()
162 dict_keys(...)
163
164 >>> source = ''.join([e.source for e in request._pyfuncitem.dtest.examples][:3])
165 >>> pytester = request.getfixturevalue('pytester')
166
167 >>> pytester.makepyfile(**{'whatever.py': source})
168 PosixPath(...)
169
170 >>> result = pytester.runpytest('whatever.py', '--disable-warnings')
171 ===...
172
173 >>> result.assert_outcomes(passed=1)
174 """
175 server = Server(socket_name=f"libtmux_test{next(namer)}")
176
177 def fin() -> None:
178 _reap_test_server(server.socket_name)
179
180 request.addfinalizer(fin)
181
182 return server
183
184
185 @pytest.fixture
186 def session_params() -> dict[str, t.Any]:
187 """Return default session creation parameters.
188
189 >>> import pytest
190 >>> from libtmux.session import Session
191
192 >>> @pytest.fixture
193 ... def session_params(session_params):
194 ... return {
195 ... 'x': 800,
196 ... 'y': 600,
197 ... }
198
199 >>> def test_example(session: "Session") -> None:
200 ... assert isinstance(session.name, str)
201 ... assert session.name.startswith('libtmux_')
202 ... window = session.new_window(window_name='new one')
203 ... assert window.name == 'new one'
204
205 .. ::
206 >>> locals().keys()
207 dict_keys(...)
208
209 >>> source = ''.join([e.source for e in request._pyfuncitem.dtest.examples][:4])
210 >>> pytester = request.getfixturevalue('pytester')
211
212 >>> pytester.makepyfile(**{'whatever.py': source})
213 PosixPath(...)
214
215 >>> result = pytester.runpytest('whatever.py', '--disable-warnings')
216 ===...
217
218 >>> result.assert_outcomes(passed=1)
219 """
220 return {}
221
222
223 @pytest.fixture
224 def session(
225 request: pytest.FixtureRequest,
226 session_params: dict[str, t.Any],
227 server: Server,
228 ) -> Session:
229 """Return new, temporary :class:`libtmux.Session`.
230
231 >>> from libtmux.session import Session
232
233 >>> def test_example(session: "Session") -> None:
234 ... assert isinstance(session.name, str)
235 ... assert session.name.startswith('libtmux_')
236 ... window = session.new_window(window_name='new one')
237 ... assert window.name == 'new one'
238
239 .. ::
240 >>> locals().keys()
241 dict_keys(...)
242
243 >>> source = ''.join([e.source for e in request._pyfuncitem.dtest.examples][:3])
244 >>> pytester = request.getfixturevalue('pytester')
245
246 >>> pytester.makepyfile(**{'whatever.py': source})
247 PosixPath(...)
248
249 >>> result = pytester.runpytest('whatever.py', '--disable-warnings')
250 ===...
251
252 >>> result.assert_outcomes(passed=1)
253 """
254 session_name = "tmuxp"
255
256 if not server.has_session(session_name):
257 server.new_session(
258 session_name=session_name,
259 )
260
261 # find current sessions prefixed with tmuxp
262 old_test_sessions = []
263 for s in server.sessions:
264 old_name = s.session_name
265 if old_name is not None and old_name.startswith(TEST_SESSION_PREFIX):
266 old_test_sessions.append(old_name)
267
268 TEST_SESSION_NAME = get_test_session_name(server=server)
269
270 session = server.new_session(
271 session_name=TEST_SESSION_NAME,
272 **session_params,
273 )
274
275 """
276 Make sure that tmuxp can :ref:`test_builder_visually` and switches to
277 the newly created session for that testcase.
278 """
279 session_id = session.session_id
280 assert session_id is not None
281
282 with contextlib.suppress(exc.LibTmuxException):
283 server.switch_client(target_session=session_id)
284
285 for old_test_session in old_test_sessions:
286 server.kill_session(old_test_session)
287 logger.debug(
288 "old test session killed",
289 extra={
290 "tmux_session": old_test_session,
291 "tmux_subcommand": "kill-session",
292 },
293 )
294 assert session.session_name == TEST_SESSION_NAME
295 assert TEST_SESSION_NAME != "tmuxp"
296
297 return session
298
299
300 @pytest.fixture
301 def control_mode(
302 server: Server,
303 session: Session,
304 ) -> t.Callable[[], ControlMode]:
305 """Return :class:`ControlMode` context manager factory.
306
307 Returns a callable that creates :class:`ControlMode` context managers
308 bound to the test's server and session. Use as a context manager to
309 spawn a control-mode tmux client.
310
311 While the control-mode client is active, ``Server.list_clients()``
312 will include it.
313
314 Examples
315 --------
316 >>> from libtmux._internal.control_mode import ControlMode
317 >>> def test_example(control_mode):
318 ... with control_mode() as ctl:
319 ... assert ctl.client_name != ''
320 """
321 return functools.partial(ControlMode, server=server, session=session)
322
323
324 @pytest.fixture
325 def TestServer(
326 request: pytest.FixtureRequest,
327 ) -> type[Server]:
328 """Create a temporary tmux server that cleans up after itself.
329
330 This is similar to the server pytest fixture, but can be used outside of pytest.
331 The server will be killed when the test completes.
332
333 Examples
334 --------
335 >>> server = Server() # Create server instance
336 >>> server.new_session()
337 Session($... ...)
338 >>> server.is_alive()
339 True
340 >>> # Each call creates a new server with unique socket
341 >>> server2 = Server()
342 >>> server2.socket_name != server.socket_name
343 True
344 """
345 created_sockets: list[str] = []
346
347 def on_init(server: Server) -> None:
348 """Track created servers for cleanup."""
349 created_sockets.append(server.socket_name or "default")
350
351 def socket_name_factory() -> str:
352 """Generate unique socket names."""
353 return f"libtmux_test{next(namer)}"
354
355 def fin() -> None:
356 """Kill all servers created with these sockets and unlink their sockets."""
357 for socket_name in created_sockets:
358 _reap_test_server(socket_name)
359
360 request.addfinalizer(fin)
361
362 return t.cast(
363 "type[Server]",
364 functools.partial(
365 Server,
366 on_init=on_init,
367 socket_name_factory=socket_name_factory,
368 ),
369 )