Debian Codegraph @

tests/test_group_extractors.py

raw symbols SCIP
1 import sys
2 from types import ModuleType
3
4 import pytest
5
6 from cyclopts import App, Group, Parameter
7 from cyclopts.command_spec import CommandSpec
8 from cyclopts.group_extractors import RegisteredCommand, groups_from_app
9
10
11 def test_groups_annotated_invalid_recursive_definition():
12 """A default_parameter isn't allowed to have a group set, as it would introduce a paradox."""
13 default_parameter = Parameter(group="Drink") # pyright: ignore[reportGeneralTypeIssues]
14 with pytest.raises(ValueError):
15 Group("Food", default_parameter=default_parameter)
16
17
18 def test_groups_from_app_implicit():
19 def validator(argument_collection):
20 pass
21
22 app = App(help_flags=[], version_flags=[])
23
24 @app.command(group="Food")
25 def food1():
26 pass
27
28 @app.command(group=Group("Food", validator=validator))
29 def food2():
30 pass
31
32 @app.command(group="Drink")
33 def drink1():
34 pass
35
36 actual_groups = groups_from_app(app)
37 assert actual_groups == [
38 (Group("Drink"), [RegisteredCommand(("drink1",), app["drink1"])]),
39 (
40 Group("Food", validator=validator),
41 [RegisteredCommand(("food1",), app["food1"]), RegisteredCommand(("food2",), app["food2"])],
42 ),
43 ]
44
45
46 def test_commands_groups_name_collision(app):
47 @app.command(group=Group("Foo"))
48 def foo():
49 pass
50
51 @app.command(group=Group("Foo"))
52 def bar():
53 pass
54
55 with pytest.raises(ValueError):
56 groups_from_app(app)
57
58
59 def test_app_registered_with_multiple_names():
60 """Test that when an app is registered with custom names, all names are collected."""
61 app = App(help_flags=[], version_flags=[])
62 sub = App()
63
64 app.command(sub, name="foo", alias=["bar", "baz"])
65
66 # Verify that sub's internal name wasn't mutated during registration
67 assert sub._name is None
68
69 groups = groups_from_app(app)
70 assert len(groups) == 1
71 assert len(groups[0][1]) == 1
72
73 registered_command = groups[0][1][0]
74 assert set(registered_command.names) == {"foo", "bar", "baz"}
75 assert registered_command.app is sub
76
77
78 def test_same_app_registered_multiple_times():
79 """Test that the same app instance registered separately with different names is tracked correctly."""
80 app = App(help_flags=[], version_flags=[])
81 sub = App()
82
83 app.command(sub, name="first")
84 app.command(sub, name="second")
85
86 # Verify that sub's internal name wasn't mutated during registration
87 assert sub._name is None
88
89 groups = groups_from_app(app)
90 assert len(groups) == 1
91 assert len(groups[0][1]) == 1
92
93 registered_command = groups[0][1][0]
94 assert set(registered_command.names) == {"first", "second"}
95 assert registered_command.app is sub
96
97
98 def test_groups_from_app_resolve_lazy():
99 """Test that resolve_lazy parameter controls whether lazy commands are resolved.
100
101 With resolve_lazy=False (default), unresolved lazy commands appear as stubs
102 with their pre-specified help text but without triggering module imports.
103 With resolve_lazy=True, lazy commands are fully imported and resolved.
104 """
105 test_module = ModuleType("test_lazy_module")
106 test_module.cmd = lambda: "result" # type: ignore[attr-defined]
107 sys.modules["test_lazy_module"] = test_module
108
109 try:
110 app = App(help_flags=[], version_flags=[])
111
112 # Register a lazy command with pre-specified help
113 app.command("test_lazy_module:cmd", name="lazy-cmd", help="Lazy help text.")
114
115 # Also register a regular command
116 @app.command
117 def regular():
118 pass
119
120 # Verify lazy command is not resolved
121 assert isinstance(app._commands["lazy-cmd"], CommandSpec)
122 assert not app._commands["lazy-cmd"].is_resolved
123
124 # With resolve_lazy=False (default), lazy commands appear as stubs
125 groups = groups_from_app(app, resolve_lazy=False)
126 all_names = [name for _, cmds in groups for cmd in cmds for name in cmd.names]
127 assert "regular" in all_names
128 assert "lazy-cmd" in all_names
129
130 # The stub should carry the pre-specified help text
131 lazy_cmds = [cmd for _, cmds in groups for cmd in cmds if "lazy-cmd" in cmd.names]
132 assert len(lazy_cmds) == 1
133 assert isinstance(lazy_cmds[0].app, CommandSpec)
134 assert lazy_cmds[0].app.help == "Lazy help text."
135
136 # Lazy command should still be unresolved (stub, not imported)
137 assert not app._commands["lazy-cmd"].is_resolved
138
139 # With resolve_lazy=True, should include fully resolved lazy commands
140 groups = groups_from_app(app, resolve_lazy=True)
141 all_names = [name for _, cmds in groups for cmd in cmds for name in cmd.names]
142 assert "regular" in all_names
143 assert "lazy-cmd" in all_names
144
145 # Lazy command should now be resolved
146 assert app._commands["lazy-cmd"].is_resolved
147 finally:
148 del sys.modules["test_lazy_module"]
149
150
151 def test_groups_from_app_lazy_hidden():
152 """Test that lazy commands with show=False are excluded from groups."""
153 test_module = ModuleType("test_lazy_module_hidden")
154 test_module.cmd = lambda: "result" # type: ignore[attr-defined]
155 sys.modules["test_lazy_module_hidden"] = test_module
156
157 try:
158 app = App(help_flags=[], version_flags=[])
159
160 # Register a hidden lazy command
161 app.command("test_lazy_module_hidden:cmd", name="hidden-cmd", show=False)
162
163 # Also register a visible regular command
164 @app.command
165 def visible():
166 pass
167
168 groups = groups_from_app(app, resolve_lazy=False)
169 all_names = [name for _, cmds in groups for cmd in cmds for name in cmd.names]
170 assert "visible" in all_names
171 assert "hidden-cmd" not in all_names
172
173 # Should not have resolved the hidden command
174 assert isinstance(app._commands["hidden-cmd"], CommandSpec)
175 assert not app._commands["hidden-cmd"].is_resolved
176 finally:
177 del sys.modules["test_lazy_module_hidden"]
178
179
180 def test_groups_from_app_lazy_custom_group():
181 """Test that lazy commands with group= are placed in the correct group."""
182 test_module = ModuleType("test_lazy_module_group")
183 test_module.cmd = lambda: "result" # type: ignore[attr-defined]
184 sys.modules["test_lazy_module_group"] = test_module
185
186 try:
187 admin_group = Group("Admin")
188 app = App(help_flags=[], version_flags=[])
189
190 # Register a lazy command with a custom group
191 app.command("test_lazy_module_group:cmd", name="admin-cmd", group=admin_group, help="Admin command.")
192
193 # Also register a regular command (no custom group)
194 @app.command
195 def regular():
196 pass
197
198 groups = groups_from_app(app, resolve_lazy=False)
199
200 # Find the Admin group and default Commands group
201 admin_cmds = [cmd for g, cmds in groups if g.name == "Admin" for cmd in cmds]
202 default_cmds = [cmd for g, cmds in groups if g.name == "Commands" for cmd in cmds]
203
204 assert len(admin_cmds) == 1
205 assert "admin-cmd" in admin_cmds[0].names
206 assert isinstance(admin_cmds[0].app, CommandSpec)
207
208 assert len(default_cmds) == 1
209 assert "regular" in default_cmds[0].names
210
211 # Should not have resolved the lazy command
212 assert isinstance(app._commands["admin-cmd"], CommandSpec)
213 assert not app._commands["admin-cmd"].is_resolved
214 finally:
215 del sys.modules["test_lazy_module_group"]
216
217
218 def test_groups_from_app_lazy_custom_group_string():
219 """Test that lazy commands with group= as a string work correctly."""
220 test_module = ModuleType("test_lazy_module_group_str")
221 test_module.cmd = lambda: "result" # type: ignore[attr-defined]
222 sys.modules["test_lazy_module_group_str"] = test_module
223
224 try:
225 app = App(help_flags=[], version_flags=[])
226
227 # Register a lazy command with a string group name
228 app.command("test_lazy_module_group_str:cmd", name="grouped-cmd", group="Extras", help="Extra command.")
229
230 groups = groups_from_app(app, resolve_lazy=False)
231
232 extras_cmds = [cmd for g, cmds in groups if g.name == "Extras" for cmd in cmds]
233 assert len(extras_cmds) == 1
234 assert "grouped-cmd" in extras_cmds[0].names
235
236 assert isinstance(app._commands["grouped-cmd"], CommandSpec)
237 assert not app._commands["grouped-cmd"].is_resolved
238 finally:
239 del sys.modules["test_lazy_module_group_str"]