From 03d0c7e874ee658cd416acf17ec1a28838eb580b Mon Sep 17 00:00:00 2001 From: "Felix Exner (fexner)" Date: Tue, 30 Jan 2024 20:55:34 +0100 Subject: [PATCH] Add tests for parts of the create_session module (#45) --- .github/workflows/coverage.yaml | 2 +- catmux/catmux_create_session.py | 91 ++++++++++++++++------------- setup.py | 10 ++++ test/test_create_session.py | 100 ++++++++++++++++++++++++++++++++ 4 files changed, 163 insertions(+), 40 deletions(-) create mode 100644 test/test_create_session.py diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index c0affe9..dcb5eb2 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -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 . diff --git a/catmux/catmux_create_session.py b/catmux/catmux_create_session.py index 25c0c85..2371099 100644 --- a/catmux/catmux_create_session.py +++ b/catmux/catmux_create_session.py @@ -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): @@ -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: diff --git a/setup.py b/setup.py index 263434c..21c5ef5 100644 --- a/setup.py +++ b/setup.py @@ -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", @@ -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"]}, ) diff --git a/test/test_create_session.py b/test/test_create_session.py new file mode 100644 index 0000000..4d29ed0 --- /dev/null +++ b/test/test_create_session.py @@ -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 + )