Skip to content

CLI Tests: Refactor to tests/cli #858

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ $ pipx install --suffix=@next 'tmuxp' --pip-args '\--pre' --force

<!-- Maintainers, insert changes / features for the next release here -->

### Internal improvements

- CLI Tests: Refactor `tests/cli` (#858)

- Fix resolution of direcotries

## tmuxp 1.23.0 (_yanked_, 2022-12-28)

_Yanked release: `tmuxp load` issues, see #856_
Expand Down
Empty file added tests/cli/__init__.py
Empty file.
139 changes: 139 additions & 0 deletions tests/cli/test_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import argparse
import os
import pathlib
import typing as t

import pytest

import libtmux
from libtmux.server import Server
from tmuxp import cli
from tmuxp.cli.import_config import get_teamocil_dir, get_tmuxinator_dir
from tmuxp.cli.load import _reattach, load_plugins
from tmuxp.cli.utils import tmuxp_echo
from tmuxp.config_reader import ConfigReader
from tmuxp.workspace import loader
from tmuxp.workspace.builder import WorkspaceBuilder
from tmuxp.workspace.finders import find_workspace_file

from ..fixtures import utils as test_utils

if t.TYPE_CHECKING:
import _pytest.capture


def test_creates_config_dir_not_exists(tmp_path: pathlib.Path) -> None:
"""cli.startup() creates config dir if not exists."""

cli.startup(tmp_path)
assert os.path.exists(tmp_path)


@pytest.mark.parametrize(
"cli_args",
[
(["--help"]),
(["-h"]),
],
)
def test_help(
cli_args: t.List[str],
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture,
) -> None:
try:
cli.cli(cli_args)
except SystemExit:
pass
result = capsys.readouterr()

assert "usage: tmuxp [-h] [--version] [--log-level log-level]" in result.out


def test_resolve_behavior(
tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch
) -> None:
expect = tmp_path
monkeypatch.chdir(tmp_path)
assert pathlib.Path("../").resolve() == pathlib.Path(os.path.dirname(expect))
assert pathlib.Path(".").resolve() == expect
assert pathlib.Path("./").resolve() == expect
assert pathlib.Path(expect).resolve() == expect


def test_get_tmuxinator_dir(monkeypatch: pytest.MonkeyPatch) -> None:
assert get_tmuxinator_dir() == os.path.expanduser("~/.tmuxinator/")

monkeypatch.setenv("HOME", "/moo")
assert get_tmuxinator_dir() == "/moo/.tmuxinator/"
assert get_tmuxinator_dir() == os.path.expanduser("~/.tmuxinator/")


def test_get_teamocil_dir(monkeypatch: pytest.MonkeyPatch) -> None:
assert get_teamocil_dir() == os.path.expanduser("~/.teamocil/")

monkeypatch.setenv("HOME", "/moo")
assert get_teamocil_dir() == "/moo/.teamocil/"
assert get_teamocil_dir() == os.path.expanduser("~/.teamocil/")


def test_pass_config_dir_ClickPath(
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture,
) -> None:

configdir = tmp_path / "myconfigdir"
configdir.mkdir()
user_config_name = "myconfig"
user_config = configdir / f"{user_config_name}.yaml"
user_config.touch()

expect = str(user_config)

parser = argparse.ArgumentParser()
parser.add_argument("workspace_file", type=str)

def config_cmd(workspace_file: str) -> None:
tmuxp_echo(find_workspace_file(workspace_file, workspace_dir=configdir))

def check_cmd(config_arg) -> "_pytest.capture.CaptureResult":
args = parser.parse_args([config_arg])
config_cmd(workspace_file=args.workspace_file)
return capsys.readouterr()

monkeypatch.chdir(configdir)

assert expect in check_cmd("myconfig").out
assert expect in check_cmd("myconfig.yaml").out
assert expect in check_cmd("./myconfig.yaml").out
assert str(user_config) in check_cmd(str(configdir / "myconfig.yaml")).out

with pytest.raises(FileNotFoundError):
assert "FileNotFoundError" in check_cmd(".tmuxp.json").out


def test_reattach_plugins(
monkeypatch_plugin_test_packages: None, server: "Server"
) -> None:
config_plugins = test_utils.read_workspace_file("workspace/builder/plugin_r.yaml")

sconfig = ConfigReader._load(format="yaml", content=config_plugins)
sconfig = loader.expand(sconfig)

# open it detached
builder = WorkspaceBuilder(
sconf=sconfig, plugins=load_plugins(sconfig), server=server
)
builder.build()

try:
_reattach(builder)
except libtmux.exc.LibTmuxException:
pass

assert builder.session is not None
proc = builder.session.cmd("display-message", "-p", "'#S'")

assert proc.stdout[0] == "'plugin_test_r'"
86 changes: 86 additions & 0 deletions tests/cli/test_convert.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import io
import json
import pathlib
import typing as t

import pytest

from tmuxp import cli


@pytest.mark.parametrize(
"cli_args",
[
(["convert", "."]),
(["convert", ".tmuxp.yaml"]),
(["convert", ".tmuxp.yaml", "-y"]),
(["convert", ".tmuxp.yml"]),
(["convert", ".tmuxp.yml", "-y"]),
],
)
def test_convert(
cli_args: t.List[str],
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
# create dummy tmuxp yaml so we don't get yelled at
filename = cli_args[1]
if filename == ".":
filename = ".tmuxp.yaml"
file_ext = filename.rsplit(".", 1)[-1]
assert file_ext in ["yaml", "yml"], file_ext
workspace_file_path = tmp_path / filename
workspace_file_path.write_text("\nsession_name: hello\n", encoding="utf-8")
oh_my_zsh_path = tmp_path / ".oh-my-zsh"
oh_my_zsh_path.mkdir()
monkeypatch.setenv("HOME", str(tmp_path))

monkeypatch.chdir(tmp_path)

# If autoconfirm (-y) no need to prompt y
input_args = "y\ny\n" if "-y" not in cli_args else ""

monkeypatch.setattr("sys.stdin", io.StringIO(input_args))
try:
cli.cli(cli_args)
except SystemExit:
pass
tmuxp_json = tmp_path / ".tmuxp.json"
assert tmuxp_json.exists()
assert tmuxp_json.open().read() == json.dumps({"session_name": "hello"}, indent=2)


@pytest.mark.parametrize(
"cli_args",
[
(["convert", "."]),
(["convert", ".tmuxp.json"]),
(["convert", ".tmuxp.json", "-y"]),
],
)
def test_convert_json(
cli_args: t.List[str],
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
# create dummy tmuxp yaml so we don't get yelled at
json_config = tmp_path / ".tmuxp.json"
json_config.write_text('{"session_name": "hello"}', encoding="utf-8")
oh_my_zsh_path = tmp_path / ".oh-my-zsh"
oh_my_zsh_path.mkdir()
monkeypatch.setenv("HOME", str(tmp_path))

monkeypatch.chdir(tmp_path)

# If autoconfirm (-y) no need to prompt y
input_args = "y\ny\n" if "-y" not in cli_args else ""

monkeypatch.setattr("sys.stdin", io.StringIO(input_args))
try:
cli.cli(cli_args)
except SystemExit:
pass

tmuxp_yaml = tmp_path / ".tmuxp.yaml"
assert tmuxp_yaml.exists()
assert tmuxp_yaml.open().read() == "session_name: hello\n"
30 changes: 30 additions & 0 deletions tests/cli/test_debug_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import pathlib

import pytest

from tmuxp import cli


def test_debug_info_cli(
monkeypatch: pytest.MonkeyPatch,
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture,
) -> None:
monkeypatch.setenv("SHELL", "/bin/bash")

cli.cli(["debug-info"])
cli_output = capsys.readouterr().out
assert "environment" in cli_output
assert "python version" in cli_output
assert "system PATH" in cli_output
assert "tmux version" in cli_output
assert "libtmux version" in cli_output
assert "tmuxp version" in cli_output
assert "tmux path" in cli_output
assert "tmuxp path" in cli_output
assert "shell" in cli_output
assert "tmux session" in cli_output
assert "tmux windows" in cli_output
assert "tmux panes" in cli_output
assert "tmux global options" in cli_output
assert "tmux window options" in cli_output
105 changes: 105 additions & 0 deletions tests/cli/test_freeze.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import io
import pathlib
import typing as t

import pytest

from libtmux.server import Server
from tmuxp import cli
from tmuxp.config_reader import ConfigReader


@pytest.mark.parametrize(
"cli_args,inputs",
[
(["freeze", "myfrozensession"], ["y\n", "./la.yaml\n", "y\n"]),
( # Exists
["freeze", "myfrozensession"],
["y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"],
),
( # Imply current session if not entered
["freeze"],
["y\n", "./la.yaml\n", "y\n"],
),
(["freeze"], ["y\n", "./exists.yaml\n", "./la.yaml\n", "y\n"]), # Exists
],
)
def test_freeze(
server: "Server",
cli_args: t.List[str],
inputs: t.List[str],
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
exists_yaml = tmp_path / "exists.yaml"
exists_yaml.touch()

server.new_session(session_name="myfirstsession")
server.new_session(session_name="myfrozensession")

# Assign an active pane to the session
second_session = server.sessions[1]
first_pane_on_second_session_id = second_session.windows[0].panes[0].pane_id
assert first_pane_on_second_session_id
monkeypatch.setenv("TMUX_PANE", first_pane_on_second_session_id)

monkeypatch.chdir(tmp_path)
# Use tmux server (socket name) used in the test
assert server.socket_name is not None
cli_args = cli_args + ["-L", server.socket_name]

monkeypatch.setattr("sys.stdin", io.StringIO("".join(inputs)))
try:
cli.cli(cli_args)
except SystemExit:
pass

yaml_config_path = tmp_path / "la.yaml"
assert yaml_config_path.exists()

yaml_config = yaml_config_path.open().read()
frozen_config = ConfigReader._load(format="yaml", content=yaml_config)

assert frozen_config["session_name"] == "myfrozensession"


@pytest.mark.parametrize(
"cli_args,inputs",
[
( # Overwrite
["freeze", "mysession", "--force"],
["\n", "\n", "y\n", "./exists.yaml\n", "y\n"],
),
( # Imply current session if not entered
["freeze", "--force"],
["\n", "\n", "y\n", "./exists.yaml\n", "y\n"],
),
],
)
def test_freeze_overwrite(
server: "Server",
cli_args: t.List[str],
inputs: t.List[str],
tmp_path: pathlib.Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
exists_yaml = tmp_path / "exists.yaml"
exists_yaml.touch()

server.new_session(session_name="mysession")

monkeypatch.chdir(tmp_path)
# Use tmux server (socket name) used in the test
assert server.socket_name is not None
cli_args = cli_args + ["-L", server.socket_name]

monkeypatch.setattr("sys.stdin", io.StringIO("".join(inputs)))
try:
cli.cli(cli_args)
except SystemExit:
pass

yaml_config_path = tmp_path / "exists.yaml"
assert yaml_config_path.exists()
Loading