Skip to content

Commit 0a615e7

Browse files
committed
docs: Improve test.py
1 parent 10ec1c3 commit 0a615e7

File tree

5 files changed

+77
-87
lines changed

5 files changed

+77
-87
lines changed

src/libtmux/test/__init__.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,8 @@
1-
"""Helper methods for libtmux and downstream libtmux libraries."""
1+
"""Provide helper methods for libtmux and downstream libtmux libraries.
2+
3+
This module includes various testing utilities, context managers, and utility
4+
functions to facilitate session creation, window creation, retries, and
5+
environment variable manipulation. It preserves existing testing scenarios and
6+
patterns, ensuring stable and consistent integration tests across different
7+
libtmux-based projects.
8+
"""

src/libtmux/test/environment.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,19 @@
1919

2020

2121
class EnvironmentVarGuard:
22-
"""Mock environmental variables safely.
22+
"""Safely mock environmental variables within a context manager.
2323
24-
Helps rotect the environment variable properly. Can be used as context
25-
manager.
24+
Ensures any changes to environment variables are reverted upon exit.
2625
2726
Notes
2827
-----
29-
Vendorized to fix issue with Anaconda Python 2 not including test module,
30-
see #121 [1]_
28+
This is vendorized to address issues where some Python distributions do
29+
not include test modules such as test_support.
3130
3231
References
3332
----------
34-
.. [1] Just installed, "ImportError: cannot import name test_support".
35-
GitHub issue for tmuxp. https://github.com/tmux-python/tmuxp/issues/121.
36-
Created October 12th, 2015. Accessed April 7th, 2018.
33+
#. "ImportError: cannot import name test_support" found in certain Python
34+
distributions, see issue #121 in the tmuxp project.
3735
"""
3836

3937
def __init__(self) -> None:
@@ -42,15 +40,15 @@ def __init__(self) -> None:
4240
self._reset: dict[str, str] = {}
4341

4442
def set(self, envvar: str, value: str) -> None:
45-
"""Set environment variable."""
43+
"""Set an environment variable, preserving prior state."""
4644
if envvar not in self._environ:
4745
self._unset.add(envvar)
4846
else:
4947
self._reset[envvar] = self._environ[envvar]
5048
self._environ[envvar] = value
5149

5250
def unset(self, envvar: str) -> None:
53-
"""Unset environment variable."""
51+
"""Unset an environment variable, preserving prior state."""
5452
if envvar in self._environ:
5553
# If we previously set this variable in this context, remove it from _unset
5654
if envvar in self._unset:
@@ -61,7 +59,7 @@ def unset(self, envvar: str) -> None:
6159
del self._environ[envvar]
6260

6361
def __enter__(self) -> Self:
64-
"""Return context for for context manager."""
62+
"""Enter context manager."""
6563
return self
6664

6765
def __exit__(
@@ -70,7 +68,7 @@ def __exit__(
7068
exc_value: BaseException | None,
7169
exc_tb: types.TracebackType | None,
7270
) -> None:
73-
"""Cleanup to run after context manager finishes."""
71+
"""Exit context manager, reverting environment changes."""
7472
for envvar, value in self._reset.items():
7573
self._environ[envvar] = value
7674
for unset in self._unset:

src/libtmux/test/random.py

+25-29
Original file line numberDiff line numberDiff line change
@@ -26,52 +26,51 @@
2626

2727

2828
class RandomStrSequence:
29-
"""Factory to generate random string."""
29+
"""Generate random string values (8 chars each) from a given character set.
30+
31+
Examples
32+
--------
33+
>>> rng = RandomStrSequence() # pragma: no cover
34+
>>> next(rng) # pragma: no cover
35+
'...'
36+
>>> len(next(rng)) # pragma: no cover
37+
8
38+
>>> type(next(rng)) # pragma: no cover
39+
<class 'str'>
40+
"""
3041

3142
def __init__(
3243
self,
3344
characters: str = "abcdefghijklmnopqrstuvwxyz0123456789_",
3445
) -> None:
35-
"""Create a random letter / number generator. 8 chars in length.
36-
37-
>>> rng = RandomStrSequence() # pragma: no cover
38-
>>> next(rng) # pragma: no cover
39-
'...'
40-
>>> len(next(rng)) # pragma: no cover
41-
8
42-
>>> type(next(rng)) # pragma: no cover
43-
<class 'str'>
44-
"""
4546
self.characters: str = characters
4647

4748
def __iter__(self) -> RandomStrSequence:
48-
"""Return self."""
49+
"""Return self as iterator."""
4950
return self
5051

5152
def __next__(self) -> str:
52-
"""Return next random string."""
53+
"""Return next random 8-character string."""
5354
return "".join(random.sample(self.characters, k=8))
5455

5556

5657
namer = RandomStrSequence()
5758

5859

5960
def get_test_session_name(server: Server, prefix: str = TEST_SESSION_PREFIX) -> str:
60-
"""
61-
Faker to create a session name that doesn't exist.
61+
"""Generate a unique session name that does not exist on the server.
6262
6363
Parameters
6464
----------
65-
server : :class:`libtmux.Server`
66-
libtmux server
65+
server : Server
66+
The tmux server instance.
6767
prefix : str
68-
prefix for sessions (e.g. ``libtmux_``). Defaults to
69-
``TEST_SESSION_PREFIX``.
68+
Prefix for the generated session name. Defaults to 'libtmux_'.
7069
7170
Returns
7271
-------
7372
str
74-
Random session name guaranteed to not collide with current ones.
73+
Random session name guaranteed not to collide with existing sessions.
7574
7675
Examples
7776
--------
@@ -96,22 +95,19 @@ def get_test_window_name(
9695
prefix: str | None = TEST_SESSION_PREFIX,
9796
) -> str:
9897
"""
99-
Faker to create a window name that doesn't exist.
98+
Generate a unique window name that does not exist in the given session.
10099
101100
Parameters
102101
----------
103-
session : :class:`libtmux.Session`
104-
libtmux session
105-
prefix : str
106-
prefix for windows (e.g. ``libtmux_``). Defaults to
107-
``TEST_SESSION_PREFIX``.
108-
109-
ATM we reuse the test session prefix here.
102+
session : Session
103+
The tmux session instance.
104+
prefix : str, optional
105+
Prefix for the generated window name. Defaults to 'libtmux_'.
110106
111107
Returns
112108
-------
113109
str
114-
Random window name guaranteed to not collide with current ones.
110+
Random window name guaranteed not to collide with existing windows.
115111
116112
Examples
117113
--------

src/libtmux/test/retry.py

+14-15
Original file line numberDiff line numberDiff line change
@@ -29,22 +29,21 @@ def retry_until(
2929
interval: float = RETRY_INTERVAL_SECONDS,
3030
raises: bool | None = True,
3131
) -> bool:
32-
"""
33-
Retry a function until a condition meets or the specified time passes.
32+
r"""Retry a function until it returns True or time expires.
3433
3534
Parameters
3635
----------
3736
fun : callable
38-
A function that will be called repeatedly until it returns ``True`` or
39-
the specified time passes.
40-
seconds : float
41-
Seconds to retry. Defaults to ``8``, which is configurable via
42-
``RETRY_TIMEOUT_SECONDS`` environment variables.
43-
interval : float
44-
Time in seconds to wait between calls. Defaults to ``0.05`` and is
45-
configurable via ``RETRY_INTERVAL_SECONDS`` environment variable.
46-
raises : bool
47-
Whether or not to raise an exception on timeout. Defaults to ``True``.
37+
A function that will be called repeatedly until it returns True or the
38+
specified time passes.
39+
seconds : float, optional
40+
Time limit for retries. Defaults to 8 seconds or the environment
41+
variable `RETRY_TIMEOUT_SECONDS`.
42+
interval : float, optional
43+
Time in seconds to wait between calls. Defaults to 0.05 or
44+
`RETRY_INTERVAL_SECONDS`.
45+
raises : bool, optional
46+
Whether to raise :exc:`WaitTimeout` on timeout. Defaults to True.
4847
4948
Examples
5049
--------
@@ -59,11 +58,11 @@ def retry_until(
5958
6059
>>> assert retry_until(fn, raises=False)
6160
"""
62-
ini = time.time()
61+
start_time = time.time()
6362

6463
while not fun():
65-
end = time.time()
66-
if end - ini >= seconds:
64+
now = time.time()
65+
if now - start_time >= seconds:
6766
if raises:
6867
raise WaitTimeout
6968
return False

src/libtmux/test/temporary.py

+20-30
Original file line numberDiff line numberDiff line change
@@ -29,28 +29,25 @@ def temp_session(
2929
**kwargs: t.Any,
3030
) -> Generator[Session, t.Any, t.Any]:
3131
"""
32-
Return a context manager with a temporary session.
32+
Provide a context manager for a temporary session, killed on exit.
3333
34-
If no ``session_name`` is entered, :func:`get_test_session_name` will make
35-
an unused session name.
36-
37-
The session will destroy itself upon closing with :meth:`Session.session()`.
34+
If no ``session_name`` is specified, :func:`get_test_session_name` will
35+
generate an unused one. The session is destroyed upon exiting the context
36+
manager.
3837
3938
Parameters
4039
----------
41-
server : :class:`libtmux.Server`
42-
43-
Other Parameters
44-
----------------
40+
server : Server
41+
The tmux server instance.
4542
args : list
46-
Arguments passed into :meth:`Server.new_session`
43+
Additional positional arguments for :meth:`Server.new_session`.
4744
kwargs : dict
48-
Keyword arguments passed into :meth:`Server.new_session`
45+
Keyword arguments for :meth:`Server.new_session`.
4946
5047
Yields
5148
------
52-
:class:`libtmux.Session`
53-
Temporary session
49+
Session
50+
The newly created temporary session.
5451
5552
Examples
5653
--------
@@ -80,37 +77,32 @@ def temp_window(
8077
**kwargs: t.Any,
8178
) -> Generator[Window, t.Any, t.Any]:
8279
"""
83-
Return a context manager with a temporary window.
84-
85-
The window will destroy itself upon closing with :meth:`window.
86-
kill()`.
80+
Provide a context manager for a temporary window, killed on exit.
8781
88-
If no ``window_name`` is entered, :func:`get_test_window_name` will make
89-
an unused window name.
82+
If no ``window_name`` is specified, :func:`get_test_window_name` will
83+
generate an unused one. The window is destroyed upon exiting the context
84+
manager.
9085
9186
Parameters
9287
----------
93-
session : :class:`libtmux.Session`
94-
95-
Other Parameters
96-
----------------
88+
session : Session
89+
The tmux session instance.
9790
args : list
98-
Arguments passed into :meth:`Session.new_window`
91+
Additional positional arguments for :meth:`Session.new_window`.
9992
kwargs : dict
100-
Keyword arguments passed into :meth:`Session.new_window`
93+
Keyword arguments for :meth:`Session.new_window`.
10194
10295
Yields
10396
------
104-
:class:`libtmux.Window`
105-
temporary window
97+
Window
98+
The newly created temporary window.
10699
107100
Examples
108101
--------
109102
>>> with temp_window(session) as window:
110103
... window
111104
Window(@2 2:... Session($1 libtmux_...))
112105
113-
114106
>>> with temp_window(session) as window:
115107
... window.split()
116108
Pane(%4 Window(@3 2:libtmux_..., Session($1 libtmux_...)))
@@ -121,8 +113,6 @@ def temp_window(
121113
window_name = kwargs.pop("window_name")
122114

123115
window = session.new_window(window_name, *args, **kwargs)
124-
125-
# Get ``window_id`` before returning it, it may be killed within context.
126116
window_id = window.window_id
127117
assert window_id is not None
128118
assert isinstance(window_id, str)

0 commit comments

Comments
 (0)