-
Notifications
You must be signed in to change notification settings - Fork 104
/
test_options.py
538 lines (444 loc) · 16.9 KB
/
test_options.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
"""Test for libtmux options management."""
import dataclasses
import textwrap
import typing as t
import pytest
from libtmux._internal.constants import (
Options,
PaneOptions,
ServerOptions,
SessionOptions,
TmuxArray,
WindowOptions,
)
from libtmux.common import has_gte_version
from libtmux.constants import OptionScope
from libtmux.exc import OptionError
from libtmux.pane import Pane
if t.TYPE_CHECKING:
from typing_extensions import LiteralString
from libtmux.server import Server
def test_options(server: "Server") -> None:
"""Test basic options."""
session = server.new_session(session_name="test")
window = session.new_window(window_name="test")
pane = window.split_window(attach=False)
for obj in [server, session, window, pane]:
obj._show_options()
obj._show_options(_global=True)
obj._show_options(include_inherited=True)
obj._show_options(include_hooks=True)
with pytest.raises(OptionError):
obj._show_option("test")
if has_gte_version("3.0"):
obj._show_option("test", ignore_errors=True)
with pytest.raises(OptionError):
obj.set_option("test", "invalid")
if isinstance(obj, Pane):
if has_gte_version("3.0"):
obj.set_option("test", "invalid", ignore_errors=True)
else:
with pytest.raises(OptionError):
obj.set_option("test", "invalid", ignore_errors=True)
else:
obj.set_option("test", "invalid", ignore_errors=True)
def test_options_server(server: "Server") -> None:
"""Test server options."""
session = server.new_session(session_name="test")
window = session.new_window(window_name="test")
pane = window.split_window(attach=False)
server.set_option("buffer-limit", 100)
assert server._show_option("buffer-limit") == 100
if has_gte_version("3.0"):
server.set_option("buffer-limit", 150, scope=OptionScope.Pane)
if has_gte_version("3.0"):
# set-option and show-options w/ Pane (-p) does not exist until 3.0+
server.set_option(
"buffer-limit",
150,
scope=OptionScope.Pane,
ignore_errors=True,
)
server.set_option("buffer-limit", 150, scope=OptionScope.Server)
if has_gte_version("3.0"):
assert session._show_option("buffer-limit") == 150
# Server option in deeper objects
if has_gte_version("3.0"):
pane.set_option("buffer-limit", 100)
else:
with pytest.raises(OptionError):
pane.set_option("buffer-limit", 100)
if has_gte_version("3.0"):
assert pane._show_option("buffer-limit") == 100
assert window._show_option("buffer-limit") == 100
assert server._show_option("buffer-limit") == 100
server_options = ServerOptions(**server._show_options(scope=OptionScope.Server))
if has_gte_version("3.0"):
assert server._show_option("buffer-limit") == 100
assert server_options.buffer_limit == 100
server.set_option("buffer-limit", 150, scope=OptionScope.Server)
assert server._show_option("buffer-limit") == 150
server.unset_option("buffer-limit")
assert server._show_option("buffer-limit") == 50
def test_options_session(server: "Server") -> None:
"""Test session options."""
session = server.new_session(session_name="test")
session.new_window(window_name="test")
_session_options = session._show_options(scope=OptionScope.Session)
session_options = SessionOptions(**_session_options)
assert session_options.default_size == _session_options.get("default-size")
def test_options_window(server: "Server") -> None:
"""Test window options."""
session = server.new_session(session_name="test")
window = session.new_window(window_name="test")
window.split_window(attach=False)
_window_options = window._show_options(scope=OptionScope.Window)
window_options = WindowOptions(**_window_options)
assert window_options.automatic_rename == _window_options.get("automatic-rename")
def test_options_pane(server: "Server") -> None:
"""Test pane options."""
session = server.new_session(session_name="test")
window = session.new_window(window_name="test")
pane = window.split_window(attach=False)
_pane_options = pane._show_options(scope=OptionScope.Pane)
pane_options = PaneOptions(**_pane_options)
assert pane_options.window_active_style == _pane_options.get("window-active-style")
def test_options_grid(server: "Server") -> None:
"""Test options against grid."""
session = server.new_session(session_name="test")
window = session.new_window(window_name="test")
pane = window.split_window(attach=False)
for include_inherited in [True, False]:
for _global in [True, False]:
for obj in [server, session, window, pane]:
for scope in [
OptionScope.Server,
OptionScope.Session,
OptionScope.Window,
]:
_obj_global_options = obj._show_options(
scope=scope,
include_inherited=include_inherited,
_global=_global,
)
obj_global_options = Options(**_obj_global_options)
for field in dataclasses.fields(obj_global_options):
expected = _obj_global_options.get(field.name.replace("_", "-"))
if include_inherited and expected is None:
expected = _obj_global_options.get(
f'{field.name.replace("_", "-")}*',
None,
)
default_value = None
if field.default_factory is not dataclasses.MISSING:
default_value = field.default_factory()
if expected is None:
default_value = None
assert (
getattr(obj_global_options, field.name, default_value)
== expected
), (
f"Expect {field.name} to be {expected} when "
+ f"scope={scope}, _global={_global}"
)
if (
has_gte_version("3.0")
and scope == OptionScope.Window
and _global
):
assert obj_global_options.pane_base_index == 0
def test_custom_options(
server: "Server",
) -> None:
"""Test tmux's user (custom) options."""
session = server.new_session(session_name="test")
session.set_option("@custom-option", "test")
assert session._show_option("@custom-option") == "test"
MOCKED_GLOBAL_OPTIONS: t.List["LiteralString"] = """
backspace C-?
buffer-limit 50
command-alias[0] split-pane=split-window
command-alias[1] splitp=split-window
command-alias[2] "server-info=show-messages -JT"
command-alias[3] "info=show-messages -JT"
command-alias[4] "choose-window=choose-tree -w"
command-alias[5] "choose-session=choose-tree -s"
copy-command ''
default-terminal xterm-256color
editor vim
escape-time 50
exit-empty on
exit-unattached off
extended-keys off
focus-events off
history-file ''
message-limit 1000
prompt-history-limit 100
set-clipboard external
terminal-overrides[0] xterm-256color:Tc
terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus
terminal-features[1] screen*:title
user-keys
""".strip().split("\n")
@dataclasses.dataclass
class MockedCmdResponse:
"""Mocked tmux_cmd response."""
stdout: t.Optional[t.List["LiteralString"]]
stderr: t.Optional[t.List[str]]
def cmd_mocked(*args: object) -> MockedCmdResponse:
"""Mock command response for show-options -s (server)."""
return MockedCmdResponse(
stdout=MOCKED_GLOBAL_OPTIONS,
stderr=None,
)
def fake_cmd(
stdout: t.Optional[t.List[str]],
stderr: t.Optional[t.List[str]] = None,
) -> t.Callable[
[t.Tuple[object, ...]],
MockedCmdResponse,
]:
"""Mock command response for show-options -s (server)."""
def _cmd(*args: object) -> MockedCmdResponse:
return MockedCmdResponse(
stdout=stdout,
stderr=stderr,
)
return _cmd
def test_terminal_features(
server: "Server",
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test tmux's terminal-feature option destructuring."""
monkeypatch.setattr(server, "cmd", fake_cmd(stdout=MOCKED_GLOBAL_OPTIONS))
_options = server._show_options()
assert any("terminal-features" in k for k in _options)
options = Options(**_options)
assert options
assert options.terminal_features
assert options.terminal_features["screen*"] == ["title"]
assert options.terminal_features["xterm*"] == [
"clipboard",
"ccolour",
"cstyle",
"focus",
]
def test_terminal_overrides(
server: "Server",
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test tmux's terminal-overrides option destructuring."""
monkeypatch.setattr(server, "cmd", cmd_mocked)
_options = server._show_options()
assert any("terminal-overrides" in k for k in _options)
options = Options(**_options)
assert options
assert options.terminal_overrides
assert _options["terminal-overrides"] is not None
assert isinstance(_options["terminal-overrides"], dict)
assert not isinstance(_options["terminal-overrides"], TmuxArray)
assert "xterm-256color" in _options["terminal-overrides"]
assert isinstance(_options["terminal-overrides"]["xterm-256color"], dict)
assert _options["terminal-overrides"]["xterm-256color"] == {"Tc": None}
def test_command_alias(
server: "Server",
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test tmux's command-alias option destructuring."""
monkeypatch.setattr(server, "cmd", cmd_mocked)
_options = server._show_options()
assert any("command-alias" in k for k in _options)
options = Options(**_options)
assert options
assert options.command_alias
assert isinstance(_options["command-alias"], dict)
assert not isinstance(_options["command-alias"], TmuxArray)
assert isinstance(_options["command-alias"]["split-pane"], str)
assert _options["command-alias"]["split-pane"] == "split-window"
def test_user_keys(
server: "Server",
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test tmux's user-keys option destructuring."""
monkeypatch.setattr(server, "cmd", cmd_mocked)
_options = server._show_options()
assert any("user-keys" in k for k in _options)
options = Options(**_options)
assert options
assert options.user_keys is None
class OptionDataclassTestFixture(t.NamedTuple):
"""Test fixture raw show_option(s) data into typed libtmux data."""
# pytest internal
test_id: str
# test data
mocked_cmd_stdout: t.List[str] # option data (raw)
tmux_option: str # e.g. terminal-features
# results
expected: t.Any # e.g. 50, TerminalFeatures({}), etc.
dataclass_attribute: str # e.g. terminal_features
TEST_FIXTURES: t.List[OptionDataclassTestFixture] = [
OptionDataclassTestFixture(
test_id="terminal-features",
mocked_cmd_stdout=textwrap.dedent(
"""
terminal-features[0] xterm*:clipboard:ccolour:cstyle:focus
terminal-features[1] screen*:title
""",
)
.strip()
.split("\n"),
dataclass_attribute="terminal_features",
tmux_option="terminal-features",
expected={
"screen*": ["title"],
"xterm*": ["clipboard", "ccolour", "cstyle", "focus"],
},
),
OptionDataclassTestFixture(
test_id="command-alias",
mocked_cmd_stdout=textwrap.dedent(
"""
command-alias[0] split-pane=split-window
command-alias[1] splitp=split-window
command-alias[2] "server-info=show-messages -JT"
command-alias[3] "info=show-messages -JT"
command-alias[4] "choose-window=choose-tree -w"
command-alias[5] "choose-session=choose-tree -s"
""",
)
.strip()
.split("\n"),
dataclass_attribute="command_alias",
tmux_option="command-alias",
expected=TmuxArray(
{
"split-pane": "split-window",
"splitp": "split-window",
"server-info": "show-messages -JT",
"info": "show-messages -JT",
"choose-window": "choose-tree -w",
"choose-session": "choose-tree -s",
},
),
),
]
@pytest.mark.parametrize(
list(OptionDataclassTestFixture._fields),
TEST_FIXTURES,
ids=[test.test_id for test in TEST_FIXTURES],
)
def test_mocked_cmd_stdoutclass_fixture(
monkeypatch: pytest.MonkeyPatch,
test_id: str,
mocked_cmd_stdout: t.List[str],
tmux_option: str,
expected: t.Any,
dataclass_attribute: str,
server: "Server",
) -> None:
"""Parametrized test grid for options."""
monkeypatch.setattr(server, "cmd", fake_cmd(stdout=mocked_cmd_stdout))
_options = server._show_options()
assert any(tmux_option in k for k in _options)
options = Options(**_options)
assert options
assert hasattr(options, dataclass_attribute)
assert getattr(options, dataclass_attribute, None) == expected
@pytest.mark.parametrize(
list(OptionDataclassTestFixture._fields),
TEST_FIXTURES,
ids=[test.test_id for test in TEST_FIXTURES],
)
def test_show_option_pane_fixture(
monkeypatch: pytest.MonkeyPatch,
test_id: str,
mocked_cmd_stdout: t.List[str],
tmux_option: str,
expected: t.Any,
dataclass_attribute: str,
server: "Server",
) -> None:
"""Test Pane.show_option(s)?."""
session = server.new_session(session_name="test")
window = session.new_window(window_name="test")
pane = window.split_window(attach=False)
monkeypatch.setattr(pane, "cmd", fake_cmd(stdout=mocked_cmd_stdout))
result = pane.show_option(tmux_option)
assert result == expected
if expected is None:
assert (
result is not None
), f"Expected {expected} to be {type(expected)}, got None"
if isinstance(expected, dict):
assert isinstance(result, dict), f'Expected dict, got "{type(result)}"'
for k, v in expected.items():
assert k in result
assert result[k] == v
class SetOptionDataclassTestFixture(t.NamedTuple):
"""Test fixture raw set_option(s) data into typed libtmux data."""
# pytest internal
test_id: str
# test data
tmux_option: str # e.g. terminal-features
tmux_option_value: t.List[str] # set_option data (raw)
# results
dataclass_attribute: str # e.g. terminal_features
expected: t.Any # e.g. 50, TerminalFeatures({}), etc.
TEST_SET_OPTION_FIXTURES: t.List[SetOptionDataclassTestFixture] = [
SetOptionDataclassTestFixture(
test_id="command-alias",
tmux_option="command-alias",
tmux_option_value=textwrap.dedent(
"""
command-alias[0] split-pane=split-window
command-alias[1] splitp=split-window
command-alias[2] "server-info=show-messages -JT"
command-alias[3] "info=show-messages -JT"
command-alias[4] "choose-window=choose-tree -w"
command-alias[5] "choose-session=choose-tree -s"
""",
)
.strip()
.split("\n"),
dataclass_attribute="command_alias",
expected=TmuxArray(
{
"split-pane": "split-window",
"splitp": "split-window",
"server-info": "show-messages -JT",
"info": "show-messages -JT",
"choose-window": "choose-tree -w",
"choose-session": "choose-tree -s",
},
),
),
]
@pytest.mark.parametrize(
list(SetOptionDataclassTestFixture._fields),
TEST_SET_OPTION_FIXTURES,
ids=[test.test_id for test in TEST_SET_OPTION_FIXTURES],
)
def test_set_option_pane_fixture(
test_id: str,
tmux_option: str,
tmux_option_value: str,
dataclass_attribute: str,
expected: t.Any,
server: "Server",
) -> None:
"""Test Pane.show_option(s)?."""
session = server.new_session(session_name="test")
window = session.new_window(window_name="test")
pane = window.split_window(attach=False)
pane.set_option(tmux_option, tmux_option_value)
result = pane.show_option(tmux_option)
assert result == expected
if expected is None:
assert (
result is not None
), f"Expected {expected} to be {type(expected)}, got None"
if isinstance(expected, dict):
assert isinstance(result, dict), f'Expected dict, got "{type(result)}"'
for k, v in expected.items():
assert k in result
assert result[k] == v