Debian Codegraph @

test/test_cli.py

raw symbols SCIP
1 import argparse
2 import os
3 import platform
4 import re
5 import subprocess
6 from typing import Any
7 import unittest
8 from unittest import mock
9 from unittest.mock import MagicMock, patch
10 import pytest
11 from con_duct import cli
12 from con_duct.cli import _create_run_parser
13
14 SYSTEM = platform.system()
15
16
17 class TestSuiteHelpers(unittest.TestCase):
18
19 def test_execute_returns_int(self) -> None:
20 def return_non_int(*_args: Any) -> str:
21 return "NOPE"
22
23 args = argparse.Namespace(
24 command="invalid",
25 file_path="dummy.json",
26 func=return_non_int,
27 log_level="INFO",
28 )
29 with pytest.raises(TypeError):
30 cli.execute(args)
31
32 @patch("con_duct.cli.argparse.ArgumentParser")
33 def test_parser_mock_sanity(self, mock_parser: MagicMock) -> None:
34 mock_args = MagicMock
35 mock_args.command = None
36 mock_parser.parse_args.return_value = mock_args
37 argv = ["/path/to/con-duct", "plot", "--help"]
38 cli.main(argv)
39 mock_parser.return_value.print_help.assert_called_once()
40
41 @patch("con_duct.cli.sys.exit", new_callable=MagicMock)
42 @patch("con_duct.cli.sys.stderr", new_callable=MagicMock)
43 @patch("con_duct.cli.sys.stdout", new_callable=MagicMock)
44 def test_parser_sanity_green(
45 self, mock_stdout: MagicMock, mock_stderr: MagicMock, mock_exit: MagicMock
46 ) -> None:
47 argv = ["--help"]
48 cli.main(argv)
49 # [0][1][0]: [first call][positional args set(0 is self)][first positional]
50 out = mock_stdout.write.mock_calls[0][1][0]
51 assert "usage: con-duct <command> [options]" in out
52 mock_stderr.write.assert_not_called()
53 mock_exit.assert_called_once_with(0)
54
55 @patch("con_duct.cli.sys.exit", new_callable=MagicMock)
56 @patch("con_duct.cli.sys.stderr", new_callable=MagicMock)
57 @patch("con_duct.cli.sys.stdout", new_callable=MagicMock)
58 def test_parser_sanity_red(
59 self, mock_stdout: MagicMock, mock_stderr: MagicMock, mock_exit: MagicMock
60 ) -> None:
61 argv = ["--fakehelp"]
62 cli.main(argv)
63 # [0][1][0]: [first call][positional args set(0 is self)][first positional]
64 out = mock_stdout.write.mock_calls[0][1][0]
65 assert "usage: con-duct <command> [options]" in out
66 mock_stderr.write.ssert_not_called()
67 # First call
68 assert (
69 "usage: con-duct <command> [options]"
70 in mock_stderr.write.mock_calls[0][1][0]
71 )
72 # second call
73 assert "--fakehelp" in mock_stderr.write.mock_calls[1][1][0]
74 mock_exit.assert_called_once_with(2)
75
76
77 def test_duct_help() -> None:
78 out = subprocess.check_output(["duct", "--help", "ps"])
79 output_str = out.decode("utf-8")
80 # duct delegates to con-duct run, so usage shows con-duct run
81 assert "usage: con-duct run" in output_str
82 # Help text should mention both entry points
83 assert "'duct' or 'con-duct run'" in output_str
84
85
86 def test_duct_version() -> None:
87 out = subprocess.check_output(["duct", "--version"])
88 output_str = out.decode("utf-8").strip()
89 # duct now delegates to con-duct run, so version shows con-duct with full prog name
90 assert output_str.startswith("con-duct ")
91 # Check that it has a version pattern (version appears after prog name)
92 assert re.search(r"\d+\.\d+\.\d+", output_str)
93
94
95 def test_con_duct_version() -> None:
96 out = subprocess.check_output(["con-duct", "--version"])
97 output_str = out.decode("utf-8").strip()
98 assert output_str.startswith("con-duct ")
99 # Check that it has a version pattern
100 assert re.match(r"con-duct \d+\.\d+\.\d+", output_str)
101
102
103 @pytest.mark.skipif(SYSTEM != "Linux", reason="Test specific to Linux behavior")
104 def test_cmd_help() -> None:
105 out = subprocess.check_output(["duct", "ps", "--help"])
106 assert "ps [options]" in str(out)
107 # Should show ps help, not duct/con-duct help
108 assert "usage: con-duct <command> [options] run" not in str(out)
109
110
111 @pytest.mark.parametrize(
112 "args",
113 [
114 ["duct", "--unknown", "ps"],
115 ["duct", "--unknown", "ps", "--shouldhavenoeffect"],
116 ],
117 )
118 def test_duct_unrecognized_arg(args: list) -> None:
119 try:
120 subprocess.check_output(args, stderr=subprocess.STDOUT)
121 pytest.fail("Command should have failed with a non-zero exit code")
122 except subprocess.CalledProcessError as e:
123 assert e.returncode == 2
124 assert "error: unrecognized arguments: --unknown" in str(e.stdout)
125
126
127 def test_duct_missing_cmd() -> None:
128 try:
129 subprocess.check_output(
130 ["duct", "--sample-interval", "1"], stderr=subprocess.STDOUT
131 )
132 pytest.fail("Command should have failed with a non-zero exit code")
133 except subprocess.CalledProcessError as e:
134 assert e.returncode == 2
135 assert "error: the following arguments are required: command" in str(e.stdout)
136
137
138 @pytest.mark.skipif(SYSTEM != "Linux", reason="Test specific to Linux behavior")
139 def test_abbreviation_disabled() -> None:
140 """
141 If abbreviation is enabled, options passed to command (not duct) are still
142 filtered through the argparse and causes problems.
143 """
144 try:
145 subprocess.check_output(["duct", "ps", "--output"], stderr=subprocess.STDOUT)
146 raise AssertionError("Invocation of 'ps' should have failed")
147 except subprocess.CalledProcessError as e:
148 assert e.returncode == 1
149 assert "duct: error: ambiguous option: --output could match" not in str(
150 e.stdout
151 )
152 assert "ps [options]" in str(e.stdout)
153
154
155 @pytest.mark.parametrize(
156 "mode_arg,expected_mode",
157 [
158 ([], "new-session"), # default
159 (["--mode", "new-session"], "new-session"),
160 (["--mode", "current-session"], "current-session"),
161 ],
162 )
163 def test_mode_argument_parsing(mode_arg: list, expected_mode: str) -> None:
164 """Test that --mode argument is parsed correctly with both long and short forms."""
165 cmd_args = mode_arg + ["echo", "test"]
166 parser = _create_run_parser()
167 args = parser.parse_args(cmd_args)
168 assert str(args.mode) == expected_mode
169
170
171 def test_mode_invalid_value() -> None:
172 """Test that invalid --mode values are rejected."""
173 try:
174 subprocess.check_output(
175 ["duct", "--mode", "invalid-mode", "echo", "test"], stderr=subprocess.STDOUT
176 )
177 pytest.fail("Command should have failed with invalid mode value")
178 except subprocess.CalledProcessError as e:
179 assert e.returncode == 2
180 assert "invalid SessionMode value: 'invalid-mode'" in str(e.stdout)
181
182
183 def test_message_parsing() -> None:
184 """Test that -m/--message flag is correctly parsed."""
185 parser = _create_run_parser()
186
187 # Test short flag
188 args = parser.parse_args(["-m", "test message", "echo", "hello"])
189 assert args.message == "test message"
190 assert args.command == "echo"
191 assert args.command_args == ["hello"]
192
193 # Test long flag
194 args = parser.parse_args(["--message", "another message", "ls"])
195 assert args.message == "another message"
196 assert args.command == "ls"
197
198 # Test without message (should be empty string)
199 args = parser.parse_args(["echo", "hello"])
200 assert args.message == ""
201
202
203 def test_message_env_variable() -> None:
204 """Test that DUCT_MESSAGE environment variable is used as default."""
205 with mock.patch.dict(os.environ, {"DUCT_MESSAGE": "env message"}):
206 parser = _create_run_parser()
207 args = parser.parse_args(["echo", "hello"])
208 assert args.message == "env message"
209
210 # Command line should override env variable
211 with mock.patch.dict(os.environ, {"DUCT_MESSAGE": "env message"}):
212 parser = _create_run_parser()
213 args = parser.parse_args(["-m", "cli message", "echo", "hello"])
214 assert args.message == "cli message"