Skip to content

Commit

Permalink
Add tests for parts of the create_session module (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
fmauch authored Jan 30, 2024
1 parent e1f6ad3 commit 03d0c7e
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 40 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/coverage.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:
run: |
python -m pip install --upgrade pip
pip install pytest-cov codecov
python setup.py develop
pip install .[test]
- name: Test with pytest
run: |
pytest --cov=catmux --cov-report=xml .
Expand Down
91 changes: 52 additions & 39 deletions catmux/catmux_create_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,6 @@
import libtmux

from catmux.session import Session as CatmuxSession
import catmux.exceptions


def safe_call(cmd_list):
"""Makes a subprocess check_call and outputs a clear error message on failure and then exits"""
try:
subprocess.check_output(cmd_list)
return True
except subprocess.CalledProcessError as err_thrown:
print('Error while calling "%s"', err_thrown.cmd)
return False


def parse_arguments(debug=False):
Expand Down Expand Up @@ -80,46 +69,70 @@ def parse_arguments(debug=False):
return args


def resolve_tmux_config_path(tmux_config: str) -> str:
"""
Determine the correct tmux config to use. Uses the following priority
- If a path is passed during runtime, use that one
- If ~/.tmux.conf exists, use that one
- If /etc/tmux.conf exists, use that one
- Fallback to this package's example configuration
"""
if not tmux_config:
if os.path.exists(os.path.expanduser("~/.tmux.conf")):
tmux_config = os.path.expanduser("~/.tmux.conf")
elif os.path.exists("/etc/tmux.conf"):
tmux_config = "/etc/tmux.conf"
else:
with resources.path(
".".join(["catmux", "resources"]), "tmux_default.conf"
) as catmux_session:
tmux_config = str(catmux_session)
if not os.path.exists(tmux_config):
raise OSError(f"Given tmux_config file at '{tmux_config}' does not exist")
return tmux_config


def check_for_existing_session(tmux_server: libtmux.Server, session_name: str) -> bool:
try:
tmux_server.sessions.get(session_name=session_name)
return True
except libtmux.exc.ObjectDoesNotExist:
# If no session with that name can be found, everything is fine...
return False
raise RuntimeError()


def create_session(
tmux_server: libtmux.Server, session_config: str, session_name: str, overwrites: str
) -> CatmuxSession:
session = CatmuxSession(
session_name=session_name,
runtime_params=overwrites,
)
session.init_from_filepath(session_config)

return session.run(tmux_server)


def main():
"""Creates a new tmux session if it does not yet exist"""
args = parse_arguments()

if args.tmux_config:
tmux_config = args.tmux_config
if not os.path.exists(tmux_config):
print("Given tmux_config file does not exist")
sys.exit(1)
elif os.path.exists(os.path.expanduser("~/.tmux.conf")):
tmux_config = os.path.expanduser("~/.tmux.conf")
elif os.path.exists("/etc/tmux.conf"):
tmux_config = "/etc/tmux.conf"
else:
with resources.path(
".".join(["catmux", "resources"]), "tmux_default.conf"
) as catmux_session:
tmux_config = str(catmux_session)
print("Using tmux config file: {}".format(tmux_config))
tmux_config = resolve_tmux_config_path(args.tmux_config)
print(f"Using tmux config file: {tmux_config}")

tmux_server = libtmux.Server(args.server_name, config_file=tmux_config)
try:
tmux_server.sessions.get(session_name=args.session_name)

if check_for_existing_session(tmux_server, args.session_name):
print(
f'Session with name "{args.session_name}" already exists. Not overwriting session.'
)
sys.exit(1)
except libtmux.exc.ObjectDoesNotExist:
# If no session with that name can be found, everything is fine...
pass

session_config = CatmuxSession(
session_name=args.session_name,
runtime_params=args.overwrite,
)
try:
session_config.init_from_filepath(args.session_config)
print(f'Created session "{args.session_name}"')

target_session = session_config.run(tmux_server)
create_session(
tmux_server, args.session_config, args.session_name, args.overwrite
)
if not args.detach:
tmux_server.attach_session(target_session=args.session_name)
except Exception as err:
Expand Down
10 changes: 10 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
with open("README.md", "r") as fh:
long_description = fh.read()

test_deps = [
"pytest",
"pyfakefs",
]
extras = {
"test": test_deps,
}

setuptools.setup(
name="catmux",
version="0.3.6",
Expand All @@ -26,6 +34,8 @@
"Operating System :: OS Independent",
],
install_requires=["pyyaml", "libtmux"],
tests_require=test_deps,
extras_require=extras,
python_requires=">=3.7",
package_data={"catmux.resources": ["*.yaml", "*.txt", "*.conf"]},
)
100 changes: 100 additions & 0 deletions test/test_create_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import os
import pytest
from tempfile import mkstemp

from importlib import resources
import libtmux
import yaml

import catmux.catmux_create_session

# from catmux.session import Session


@pytest.fixture()
def tmux_server():
server = libtmux.Server(socket_name="catmux_test_96754")
yield server
server.kill_server()


def test_resolve_config_path(fs):
with pytest.raises(OSError):
catmux.catmux_create_session.resolve_tmux_config_path(
"/this/file/does/not/exist/probably"
)
with resources.path(
".".join(["catmux", "resources"]), "tmux_default.conf"
) as catmux_session:
tmux_config = str(catmux_session)
assert tmux_config == catmux.catmux_create_session.resolve_tmux_config_path(
None
)

with resources.path(
".".join(["catmux", "resources"]), "tmux_default.conf"
) as catmux_session:
tmux_config = str(catmux_session)
fs.create_file(tmux_config)
assert tmux_config == catmux.catmux_create_session.resolve_tmux_config_path(
None
)
fs.create_file(os.path.expanduser("/etc/tmux.conf"))
assert os.path.expanduser(
"/etc/tmux.conf"
) == catmux.catmux_create_session.resolve_tmux_config_path(None)
fs.create_file(os.path.expanduser("~/.tmux.conf"))
assert os.path.expanduser(
"~/.tmux.conf"
) == catmux.catmux_create_session.resolve_tmux_config_path(None)


def test_checking_for_existing_session(tmux_server):
tmux_server.new_session(session_name="foo_session")
assert (
catmux.catmux_create_session.check_for_existing_session(
tmux_server, "bar_session"
)
== False
)
assert (
catmux.catmux_create_session.check_for_existing_session(
tmux_server, "foo_session"
)
== True
)


def test_create_session(tmux_server):
session_config, file_path = mkstemp()
session_name = "test_session"
overwrites = None
with os.fdopen(session_config, "w") as f:
f.write(
"""common:
before_commands:
- echo "hello"
- echo "world"
default_window: foobar
parameters:
replacement_param: schubidoo
show_layouts: true
windows:
- name: foobar
if: show_layouts
commands:
- echo "${replacement_param}"
- name: hello
layout: tiled
delay: 1
splits:
- commands:
- echo "first_split"
- commands:
- echo "second_split"
"""
)
catmux.catmux_create_session.create_session(
tmux_server, file_path, session_name, overwrites
)

0 comments on commit 03d0c7e

Please sign in to comment.