-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_admin_source_coverage.py
More file actions
1157 lines (962 loc) · 43.7 KB
/
test_admin_source_coverage.py
File metadata and controls
1157 lines (962 loc) · 43.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import runpy
import sys
from pathlib import Path
import click
import pytest
from click.testing import CliRunner
import mcli.dev as dev_entry
from mcli.commands.admin.new_command import entry as new_command_entry
from mcli.commands.admin.rebrand import entry as rebrand_entry
from mcli.commands.admin.rm_command import entry as rm_command_entry
from mcli.loader import (
CommandGroupSpec,
CommandSpec,
LazyNestedGroup,
LazyPluginGroup,
LazySubGroup,
RootCommand,
_discover_nested_commands,
_merge_command_specs,
_merge_group_specs,
discover_merged_specs,
discover_specs,
load_click_command,
load_click_command_from_entry,
load_click_group,
load_group_meta,
load_meta,
)
from mcli.utils import metadata as metadata_mod
from mcli.utils.metadata import Metadata
def _write_rebrand_project(project_root: Path) -> None:
(project_root / "src" / "mcli" / "utils").mkdir(parents=True, exist_ok=True)
(project_root / "docs").mkdir(parents=True, exist_ok=True)
(project_root / "pyproject.toml").write_text(
"""
[project]
name = "mcli"
version = "1.0.0"
[project.scripts]
mcli = "mcli.main:main"
[tool.mcli]
name = "MyCLI"
cli_name = "mcli"
env_prefix = "MCLI_"
""".lstrip(),
encoding="utf-8",
)
(project_root / "src" / "mcli" / "utils" / "metadata.py").write_text(
"\n".join(
[
"class Metadata:",
' PACKAGE_NAME = "mcli"',
' APP_NAME = "MyCLI"',
' COMMAND_NAME = "mcli"',
"",
]
),
encoding="utf-8",
)
(project_root / "README.md").write_text(
"# MyCLI\n\nRun `mcli --help` and set MCLI_COMMANDS_DIR when needed.\n",
encoding="utf-8",
)
(project_root / "docs" / "usage.md").write_text(
"Use [tool.mcli] and mcli in examples.\n",
encoding="utf-8",
)
def test_dev_new_plugin_from_source_creates_files(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setattr(dev_entry.Metadata, "COMMANDS_DIR", commands_dir)
runner = CliRunner()
result = runner.invoke(
dev_entry.cli,
["new-plugin", "alpha", "bravo", "--short-help", "Alpha Bravo command."],
)
assert result.exit_code == 0
assert (commands_dir / "alpha" / "bravo" / "entry.py").exists()
assert (commands_dir / "alpha" / "bravo" / "meta.yaml").read_text(encoding="utf-8").strip() == (
"shortHelp: Alpha Bravo command."
)
def test_dev_new_plugin_rejects_existing_without_force(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setattr(dev_entry.Metadata, "COMMANDS_DIR", commands_dir)
target = commands_dir / "alpha" / "bravo"
target.mkdir(parents=True)
(target / "entry.py").write_text("x\n", encoding="utf-8")
runner = CliRunner()
result = runner.invoke(dev_entry.cli, ["new-plugin", "alpha", "bravo"])
assert result.exit_code == 2
assert "Plugin already exists" in result.output
def test_new_command_from_source_scaffolds_and_upgrades_parent(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
runner = CliRunner()
create_parent = runner.invoke(
new_command_entry.cli,
["ops", "--short-help", "Ops command"],
)
assert create_parent.exit_code == 0
assert "@click.command()" in (commands_dir / "ops" / "entry.py").read_text(encoding="utf-8")
create_child = runner.invoke(
new_command_entry.cli,
["deploy", "--parent", "ops", "--short-help", "Deploy command"],
)
assert create_child.exit_code == 0
parent_entry = (commands_dir / "ops" / "entry.py").read_text(encoding="utf-8")
assert "@click.group()" in parent_entry
assert (commands_dir / "ops" / "deploy" / "meta.yaml").exists()
def test_new_command_rejects_bad_parent_and_duplicate(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
runner = CliRunner()
bad_parent = runner.invoke(
new_command_entry.cli,
["deploy", "--parent", "ops..tools", "--short-help", "Deploy command"],
)
assert bad_parent.exit_code == 2
assert "Invalid --parent" in bad_parent.output
first = runner.invoke(new_command_entry.cli, ["deploy", "--short-help", "Deploy command"])
assert first.exit_code == 0
second = runner.invoke(new_command_entry.cli, ["deploy", "--short-help", "Deploy command"])
assert second.exit_code == 2
assert "Command already exists" in second.output
def test_rm_command_from_source_removes_target(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
target = commands_dir / "ops" / "deploy"
target.mkdir(parents=True)
(target / "entry.py").write_text("x\n", encoding="utf-8")
(target / "meta.yaml").write_text("short_help: x\n", encoding="utf-8")
runner = CliRunner()
result = runner.invoke(rm_command_entry.cli, ["deploy", "--parent", "ops", "--confirm"])
assert result.exit_code == 0
assert str(target) in result.output
assert not target.exists()
def test_rm_command_errors_for_missing_and_invalid_parent(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
runner = CliRunner()
invalid = runner.invoke(rm_command_entry.cli, ["deploy", "--parent", "ops..tools"])
assert invalid.exit_code == 2
assert "Invalid --parent" in invalid.output
missing = runner.invoke(rm_command_entry.cli, ["deploy", "--parent", "ops"])
assert missing.exit_code == 2
assert "Command does not exist." in missing.output
def test_rebrand_command_from_source_rewrites_files(tmp_path: Path, monkeypatch) -> None:
_write_rebrand_project(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
runner = CliRunner()
result = runner.invoke(
rebrand_entry.cli,
["--name", "Acme CLI", "--cli-cmd", "acme", "--skip-user", "--confirm"],
)
assert result.exit_code == 0
pyproject_text = (tmp_path / "pyproject.toml").read_text(encoding="utf-8")
metadata_text = (tmp_path / "src" / "mcli" / "utils" / "metadata.py").read_text(encoding="utf-8")
docs_text = (tmp_path / "docs" / "usage.md").read_text(encoding="utf-8")
assert 'name = "acme"' in pyproject_text
assert "[tool.mcli]" in pyproject_text
assert 'APP_NAME = "Acme CLI"' in metadata_text
assert 'COMMAND_NAME = "acme"' in metadata_text
assert "acme" in docs_text
def test_rebrand_noop_and_validation_branches(tmp_path: Path, monkeypatch) -> None:
_write_rebrand_project(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
runner = CliRunner()
noop = runner.invoke(
rebrand_entry.cli,
["--name", "MyCLI", "--cli-cmd", "mcli", "--skip-user", "--confirm"],
)
assert noop.exit_code == 0
assert "Branding already matches" in noop.output
invalid_cli = runner.invoke(
rebrand_entry.cli,
["--name", "MyCLI", "--cli-cmd", "bad command", "--skip-user", "--confirm"],
)
assert invalid_cli.exit_code != 0
assert "--cli/--cli-cmd" in invalid_cli.output
def test_rebrand_helpers_cover_section_rewrites() -> None:
text = '[project]\nname = "mcli"\n\n[project.scripts]\nmcli = "mcli.main:main"\n\n[tool.mcli]\nname = "MyCLI"\n'
current = rebrand_entry.BrandState(
app_name="MyCLI",
command_name="mcli",
env_prefix="MCLI_",
metadata_package_name="mcli",
project_package_name="mcli",
script_name="mcli",
tool_metadata_section="mcli",
)
rewritten = rebrand_entry._rewrite_pyproject(text, current, "Acme CLI", "acme")
assert 'name = "acme"' in rewritten
assert "[tool.mcli]" in rewritten
assert 'cli_name = "acme"' in rewritten
removed = rebrand_entry._remove_tool_section(rewritten, "mcli")
assert "[tool.mcli]" not in removed
upserted = rebrand_entry._upsert_tool_metadata_value(removed, "mcli", "name", "Acme CLI")
assert "[tool.mcli]" in upserted
assert 'name = "Acme CLI"' in upserted
with pytest.raises(click.ClickException, match=r"Missing \[build-system\]"):
rebrand_entry._replace_first_in_section("build-system", text, r"^x$", "x")
def test_rebrand_helpers_cover_misc_branches(tmp_path: Path, monkeypatch) -> None:
scripts: dict[object, object] = {"mcli": "other:main", "acme": "different:target"}
with pytest.raises(click.ClickException, match="Expected exactly one console script"):
rebrand_entry._discover_script_name(scripts, tmp_path / "pyproject.toml")
assert rebrand_entry._extract_metadata_constant('APP_NAME = "MyCLI"\n', "APP_NAME") == "MyCLI"
assert rebrand_entry._extract_metadata_constant("APP_NAME = ''\n", "APP_NAME") is None
assert rebrand_entry._extract_tool_metadata_value({"name": " MyCLI "}, "name") == "MyCLI"
assert rebrand_entry._extract_tool_metadata_value({"name": 1}, "name") is None
outside = tmp_path / "outside"
outside.mkdir(parents=True)
assert rebrand_entry._display_path(outside).endswith("outside")
monkeypatch.setattr(rebrand_entry.os, "access", lambda _path, _mode: True)
assert rebrand_entry._has_directory_rename_permissions(tmp_path / "a" / "x", tmp_path / "a" / "y") is False
def test_root_command_version_callback_from_source() -> None:
commands_dir = Path(__file__).parent.parent / "src" / "mcli" / "commands"
root = RootCommand(
commands_dir,
app_context={"COMMAND_NAME": "mcli", "VERSION": "9.9.9"},
)
runner = CliRunner()
result = runner.invoke(root, ["--version"])
assert result.exit_code == 0
assert result.output.strip() == "9.9.9"
def test_main_module_executes_dunder_main_branch(monkeypatch) -> None:
called: dict[str, bool] = {"called": False}
class DummyRoot:
def __init__(self, *_args, **_kwargs) -> None:
# Intentionally empty: this test double only needs to be constructible.
pass
def __call__(self, **_kwargs) -> None:
called["called"] = True
class DummyMetadata:
PACKAGE_ROOT_DIR = Path(".")
COMMANDS_DIR = Path(".")
USER_COMMANDS_DIR = Path(".")
PACKAGE_NAME = "mcli"
APP_NAME = "MyCLI"
COMMAND_NAME = "mcli"
VERSION = "1.0.0"
monkeypatch.setattr("sys.argv", ["mcli"])
monkeypatch.delitem(sys.modules, "mcli.main", raising=False)
monkeypatch.setattr("mcli.loader.RootCommand", DummyRoot)
monkeypatch.setattr("mcli.utils.metadata.Metadata", DummyMetadata)
runpy.run_module("mcli.main", run_name="__main__")
assert called["called"] is True
def test_new_command_private_branches(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
commands_dir.mkdir(parents=True)
original_load_template_file = new_command_entry._load_template_file
original_template_dir = new_command_entry._template_dir
with pytest.raises(SystemExit):
new_command_entry._parse_parent(" ")
with pytest.raises(SystemExit):
new_command_entry._validate_token("command", "bad!name")
with pytest.raises(SystemExit):
new_command_entry._assert_within_commands_dir(commands_dir, tmp_path / "outside")
created = new_command_entry._ensure_parent_groups(commands_dir, ["ops", "deploy"])
assert any(path.name == "meta.yaml" for path in created)
assert any(path.name == "entry.py" for path in created)
monkeypatch.setattr(new_command_entry, "_load_template_file", lambda _name: "missing-token")
with pytest.raises(SystemExit):
new_command_entry._new_command_meta_content("Help", "compute")
monkeypatch.setattr(new_command_entry, "_load_template_file", lambda _name: "{{COMMAND_NAME}}")
assert new_command_entry._new_command_entry_content("compute") == "compute"
legacy_entry = commands_dir / "legacy" / "entry.py"
legacy_entry.parent.mkdir(parents=True, exist_ok=True)
legacy_entry.write_text(new_command_entry._legacy_command_entry_content(), encoding="utf-8")
assert new_command_entry._upgrade_scaffold_command_to_group(legacy_entry) is True
monkeypatch.setattr(new_command_entry, "_load_template_file", original_load_template_file)
monkeypatch.setattr(new_command_entry, "_template_dir", lambda: tmp_path / "missing-template-dir")
with pytest.raises(SystemExit):
new_command_entry._load_template_file("entry.py")
monkeypatch.setattr(new_command_entry, "_template_dir", original_template_dir)
entry_path = commands_dir / "ops" / "entry.py"
entry_path.write_text("print('custom')\n", encoding="utf-8")
assert new_command_entry._upgrade_scaffold_command_to_group(entry_path) is False
assert new_command_entry._commands_dir(user=True) == Metadata.USER_COMMANDS_DIR
monkeypatch.delenv(Metadata.env_var("COMMANDS_DIR"), raising=False)
assert new_command_entry._commands_dir(user=False) == Metadata.USER_COMMANDS_DIR
def test_dev_private_abort_branches(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setattr(dev_entry.Metadata, "COMMANDS_DIR", commands_dir)
runner = CliRunner()
invalid = runner.invoke(dev_entry.cli, ["new-plugin", "bad!name", "ok"])
assert invalid.exit_code == 2
assert "Invalid command" in invalid.output
original_relative_to = Path.relative_to
def _boom_relative_to(self: Path, *other: Path) -> Path:
if self == commands_dir / "alpha" / "bravo":
raise ValueError("boom")
return original_relative_to(self, *other)
monkeypatch.setattr(Path, "relative_to", _boom_relative_to)
bad_path = runner.invoke(dev_entry.cli, ["new-plugin", "alpha", "bravo"])
assert bad_path.exit_code == 2
assert "within commands directory" in bad_path.output
def test_rm_command_private_branches(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
commands_dir.mkdir(parents=True)
with pytest.raises(SystemExit):
rm_command_entry._parse_parent(" ")
with pytest.raises(SystemExit):
rm_command_entry._validate_token("command", "bad!name")
with pytest.raises(SystemExit):
rm_command_entry._assert_within_commands_dir(commands_dir, tmp_path / "outside")
target = commands_dir / "ops"
target.write_text("x\n", encoding="utf-8")
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
runner = CliRunner()
result = runner.invoke(rm_command_entry.cli, ["ops"])
assert result.exit_code == 2
assert "not a command directory" in result.output
assert rm_command_entry._commands_dir(user=True) == Metadata.USER_COMMANDS_DIR
monkeypatch.delenv(Metadata.env_var("COMMANDS_DIR"), raising=False)
assert rm_command_entry._commands_dir(user=False) == Metadata.COMMANDS_DIR
def test_rebrand_validation_and_file_helpers(tmp_path: Path) -> None:
with pytest.raises(click.ClickException):
rebrand_entry._validate_display_name(" ")
with pytest.raises(click.ClickException):
rebrand_entry._validate_display_name("bad\nname")
assert rebrand_entry._validate_cli_command("Acme_CLI") == "acme_cli"
with pytest.raises(click.ClickException):
rebrand_entry._read_text(tmp_path / "missing.txt")
binary_file = tmp_path / "binary.bin"
binary_file.write_bytes(b"\x80\x81")
assert rebrand_entry._read_optional_text(binary_file) is None
assert rebrand_entry._escape_python('acme"cli') == 'acme\\"cli'
assert rebrand_entry._escape_toml('acme"cli') == 'acme\\"cli'
def test_rebrand_project_root_without_override(monkeypatch) -> None:
monkeypatch.delenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), raising=False)
root = rebrand_entry._project_root()
assert (root / "pyproject.toml").exists()
def test_rebrand_state_error_paths(tmp_path: Path) -> None:
(tmp_path / "src" / "mcli" / "utils").mkdir(parents=True)
(tmp_path / "src" / "mcli" / "utils" / "metadata.py").write_text("x = 1\n", encoding="utf-8")
(tmp_path / "pyproject.toml").write_text("[tool.x]\na = 1\n", encoding="utf-8")
with pytest.raises(click.ClickException, match=r"Missing \[project\]"):
rebrand_entry._read_brand_state(tmp_path)
(tmp_path / "pyproject.toml").write_text('[project]\nname = ""\n', encoding="utf-8")
with pytest.raises(click.ClickException, match="Missing project.name"):
rebrand_entry._read_brand_state(tmp_path)
(tmp_path / "pyproject.toml").write_text('[project]\nname = "mcli"\n', encoding="utf-8")
with pytest.raises(click.ClickException, match=r"Missing \[project.scripts\]"):
rebrand_entry._read_brand_state(tmp_path)
def test_rebrand_user_dir_validation_paths(tmp_path: Path, monkeypatch) -> None:
old_dir = tmp_path / ".mcli"
new_dir = tmp_path / ".acme"
old_dir.mkdir(parents=True)
new_dir.mkdir(parents=True)
with pytest.raises(click.ClickException, match="target already exists"):
rebrand_entry._validate_user_config_dir_rebrand(old_dir, new_dir)
new_dir.rmdir()
old_dir.rmdir()
old_dir.write_text("x\n", encoding="utf-8")
with pytest.raises(click.ClickException, match="not a directory"):
rebrand_entry._validate_user_config_dir_rebrand(old_dir, new_dir)
old_dir.unlink()
old_dir.mkdir()
monkeypatch.setattr(rebrand_entry.os, "access", lambda _path, _mode: False)
with pytest.raises(click.ClickException, match="insufficient permissions"):
rebrand_entry._validate_user_config_dir_rebrand(old_dir, new_dir)
def test_rebrand_rename_user_dir_and_no_source(tmp_path: Path) -> None:
old_dir = tmp_path / ".mcli"
new_dir = tmp_path / ".acme"
old_dir.mkdir(parents=True)
(old_dir / "x.txt").write_text("x\n", encoding="utf-8")
renamed = rebrand_entry._rename_user_config_dir(old_dir, new_dir)
assert renamed == (old_dir, new_dir)
assert not old_dir.exists()
assert new_dir.exists()
assert rebrand_entry._rename_user_config_dir(tmp_path / "none", tmp_path / "target") is None
def test_rebrand_rename_user_dir_oserror(tmp_path: Path, monkeypatch) -> None:
old_dir = tmp_path / ".mcli"
new_dir = tmp_path / ".acme"
old_dir.mkdir(parents=True)
def _raise_rename(_self: Path, _target: Path) -> None:
raise OSError("boom")
monkeypatch.setattr(Path, "rename", _raise_rename)
with pytest.raises(click.ClickException, match="Failed to rename user config directory"):
rebrand_entry._rename_user_config_dir(old_dir, new_dir)
def test_rebrand_section_helpers_more_branches() -> None:
text = '[tool.mcli]\nname = "x"\n'
assert rebrand_entry._rename_tool_section(text, "missing", "mcli") == text
assert rebrand_entry._remove_tool_section(text, "missing") == text
upsert = rebrand_entry._upsert_tool_metadata_value(text, "mcli", "cli_name", "acme")
assert 'cli_name = "acme"' in upsert
rewritten = rebrand_entry._rewrite_tool_metadata_section(
text,
current_section_name="mcli",
new_app_name="mcli",
new_command_name="mcli",
)
assert "[tool.mcli]" in rewritten
def test_rebrand_text_rewrite_equal_name_and_command() -> None:
current = rebrand_entry.BrandState(
app_name="MyCLI",
command_name="mcli",
env_prefix="MCLI_",
metadata_package_name="mcli",
project_package_name="mcli",
script_name="mcli",
tool_metadata_section="mcli",
)
text = '# MyCLI\nAPP_NAME = "MyCLI"\nCOMMAND_NAME = "mcli"\n'
rewritten = rebrand_entry._rewrite_text_branding(text, current, "acme", "acme")
assert 'APP_NAME = "acme"' in rewritten
assert 'COMMAND_NAME = "acme"' in rewritten
def test_rebrand_user_dir_path_helper_branch() -> None:
current = rebrand_entry.BrandState(
app_name="MyCLI",
command_name="mcli",
env_prefix="MCLI_",
metadata_package_name="mcli",
project_package_name="mcli",
script_name="mcli",
tool_metadata_section="mcli",
)
assert rebrand_entry._user_config_dir_paths(current, "mcli", skip_user=False) is None
assert rebrand_entry._user_config_dir_paths(current, "acme", skip_user=True) is None
def test_metadata_helper_branches(tmp_path: Path, monkeypatch) -> None:
assert metadata_mod._normalized_string(1) is None
assert metadata_mod._normalized_string(" ") is None
assert metadata_mod._normalized_string(" ok ") == "ok"
assert metadata_mod._load_pyproject(tmp_path / "missing.toml") == {}
bad = tmp_path / "bad.toml"
bad.write_text("[project\n", encoding="utf-8")
assert metadata_mod._load_pyproject(bad) == {}
assert metadata_mod.project_table({"x": 1}) == {}
assert metadata_mod.tool_tables({"tool": ["x"]}) == {}
assert metadata_mod.tool_tables({"tool": {"mcli": {"name": "x"}, "bad": 1}}) == {"mcli": {"name": "x"}}
assert metadata_mod.tool_metadata_section_name({"tool": {"mcli": {}}}) == "mcli"
assert metadata_mod.tool_metadata_section_name({"tool": {"mcli": {"cli_name": "x"}}}) == "mcli"
assert metadata_mod.tool_metadata_section_name({"tool": {"mcli": {"x": "y"}}}) is None
assert metadata_mod.tool_metadata_table({"tool": {"x": {"name": "n"}}}) == {"name": "n"}
assert metadata_mod.script_name_from_pyproject({"project": {"scripts": {}}}) is None
assert metadata_mod.script_name_from_pyproject({"project": {"scripts": {"mcli": "mcli.main:main"}}}) == "mcli"
assert metadata_mod.script_name_from_pyproject({"project": {"scripts": {1: "mcli.main:main"}}}) is None
monkeypatch.setattr(metadata_mod, "packages_distributions", lambda: {"mcli": ["mcli"]})
assert metadata_mod.inferred_package_name_from_installed_distribution("mcli.main") == "mcli"
assert metadata_mod.inferred_package_name_from_installed_distribution("") is None
assert metadata_mod.env_prefix_from_command_name(" ") == metadata_mod.DEFAULT_ENV_PREFIX
assert metadata_mod._normalize_env_prefix("abc") == "ABC_"
assert metadata_mod.user_config_dir("").name == ".mcli"
assert metadata_mod.Metadata.banner().startswith(metadata_mod.Metadata.APP_NAME)
assert metadata_mod.Metadata.PACKAGE_NAME in metadata_mod.Metadata.full_version()
assert metadata_mod.Metadata.env_var("X") == f"{metadata_mod.Metadata.ENV_PREFIX}X"
def test_loader_helper_branches(tmp_path: Path, monkeypatch) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("shortHelp: ok\n", encoding="utf-8")
assert load_meta(meta)["short_help"] == "ok"
def _raise_value_error(_self: Path, encoding: str = "utf-8") -> str: # noqa: ARG001
raise ValueError("x")
monkeypatch.setattr(Path, "read_text", _raise_value_error)
with pytest.raises(RuntimeError, match="Invalid meta.yaml"):
load_meta(meta)
def test_loader_group_meta_and_discovery_error_branches(tmp_path: Path) -> None:
group_meta = tmp_path / "meta.yaml"
group_meta.write_text("[]\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="expected mapping"):
load_group_meta(group_meta)
group_meta.write_text("shortHelp: ''\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="non-empty"):
load_group_meta(group_meta)
group_meta.write_text("other: value\n", encoding="utf-8")
assert load_group_meta(group_meta) is None
commands_dir = tmp_path / "commands"
command_dir = commands_dir / "admin"
command_dir.mkdir(parents=True)
(command_dir / "meta.yaml").write_text("[]\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="Invalid command plugins detected"):
discover_specs(commands_dir)
assert _discover_nested_commands(commands_dir, ["admin"], "mcli.commands", 0, []) == {}
def test_loader_merge_and_load_branches(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: Help\n", encoding="utf-8")
entry = tmp_path / "entry.py"
entry.write_text("import click\n@click.group()\ndef cli():\n pass\n", encoding="utf-8")
existing = CommandSpec(
name="ops",
entry_path=entry,
meta_path=meta,
import_path=["ops"],
module_name="mcli.commands.ops.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=True,
subcommands={},
no_args_is_help=False,
)
incoming = CommandSpec(
name="ops",
entry_path=entry,
meta_path=meta,
import_path=["ops"],
module_name="mcli.commands.ops.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=True,
subcommands={},
no_args_is_help=False,
)
merged = _merge_command_specs(existing, incoming)
assert merged.is_group is True
group_existing = CommandGroupSpec(
help_summary="Old",
entry_path=entry,
module_name="mcli.commands.ops.entry",
subcommands={},
hidden=False,
enabled=True,
help_group="Commands",
no_args_is_help=False,
has_meta=False,
)
group_incoming = CommandGroupSpec(
help_summary="New",
entry_path=entry,
module_name="mcli.commands.ops.entry",
subcommands={},
hidden=True,
enabled=False,
help_group="Admin",
no_args_is_help=True,
has_meta=True,
)
merged_group = _merge_group_specs(group_existing, group_incoming)
assert merged_group.help_summary == "New"
assert merged_group.hidden is True
roots = [(tmp_path / "commands", "mcli.commands"), (tmp_path / "commands" / ".." / "commands", "mcli.commands")]
assert discover_merged_specs(roots) == {}
disabled_group_spec = CommandSpec(
name="ops",
entry_path=entry,
meta_path=meta,
import_path=["ops"],
module_name="mcli.commands.ops.entry",
hidden=True,
enabled=False,
help_group="Commands",
is_group=True,
subcommands={},
no_args_is_help=False,
)
cmd = load_click_command(disabled_group_spec)
result = CliRunner().invoke(cmd, ["missing"])
assert result.exit_code == 2
missing_entry = tmp_path / "missing.py"
with pytest.raises(RuntimeError, match="Failed to import entry.py"):
load_click_group("ops", missing_entry, "mcli.commands.ops.entry")
with pytest.raises(RuntimeError, match="Failed to import entry.py"):
load_click_command_from_entry("ops", missing_entry, "mcli.commands.ops.entry")
def test_loader_lazy_group_branches(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: Help\nhidden: false\nenabled: true\n", encoding="utf-8")
entry = tmp_path / "entry.py"
entry.write_text("import click\n@click.command()\ndef cli():\n click.echo('ok')\n", encoding="utf-8")
spec = CommandSpec(
name="run",
entry_path=entry,
meta_path=meta,
import_path=["run"],
module_name="mcli.commands.run.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
)
subgroup = LazySubGroup("ops", {"run": spec})
assert subgroup.list_commands(click.Context(subgroup)) == ["run"]
assert subgroup.get_command(click.Context(subgroup), "missing") is None
base = click.Group(name="ops")
plugin_group = LazyPluginGroup(base, {"run": spec})
nested_group = LazyNestedGroup(base, {"run": spec})
assert plugin_group.list_commands(click.Context(plugin_group)) == ["run"]
assert nested_group.list_commands(click.Context(nested_group)) == ["run"]
assert plugin_group.get_command(click.Context(plugin_group), "missing") is None
assert nested_group.get_command(click.Context(nested_group), "missing") is None
def test_loader_disabled_group_callback_and_spec_loader_branches(tmp_path: Path, monkeypatch) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: Help\n", encoding="utf-8")
entry = tmp_path / "entry.py"
entry.write_text("import click\n@click.group()\ndef cli():\n pass\n", encoding="utf-8")
disabled = CommandSpec(
name="ops",
entry_path=entry,
meta_path=meta,
import_path=["ops"],
module_name="mcli.commands.ops.entry",
hidden=True,
enabled=False,
help_group="Commands",
is_group=True,
subcommands={},
no_args_is_help=False,
)
command = load_click_command(disabled)
assert command.callback is not None
with pytest.raises(SystemExit):
command.callback()
monkeypatch.setattr("mcli.loader.util.spec_from_file_location", lambda *_args, **_kwargs: None)
with pytest.raises(RuntimeError, match="Failed to import entry.py"):
load_click_command(
CommandSpec(
name="run",
entry_path=entry,
meta_path=meta,
import_path=["run"],
module_name="mcli.commands.run.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
)
)
with pytest.raises(RuntimeError, match="Failed to import entry.py"):
load_click_group("ops", entry, "mcli.commands.ops.entry")
with pytest.raises(RuntimeError, match="Failed to import entry.py"):
load_click_command_from_entry("ops", entry, "mcli.commands.ops.entry")
def test_loader_command_type_mismatch_branches(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: Help\n", encoding="utf-8")
group_entry = tmp_path / "group_entry.py"
group_entry.write_text("import click\n@click.command()\ndef cli():\n pass\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="click.Group"):
load_click_command(
CommandSpec(
name="ops",
entry_path=group_entry,
meta_path=meta,
import_path=["ops"],
module_name="mcli.commands.ops.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=True,
subcommands={},
no_args_is_help=False,
)
)
bad_entry = tmp_path / "bad_entry.py"
bad_entry.write_text("cli = 123\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="click.Command or click.Group"):
load_click_command_from_entry("ops", bad_entry, "mcli.commands.bad.entry")
def test_loader_group_meta_parse_error_branch(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("[unclosed\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="Invalid meta.yaml"):
load_group_meta(meta)
def test_loader_load_click_group_type_error_and_command_from_entry_success(tmp_path: Path) -> None:
bad_group_entry = tmp_path / "bad_group.py"
bad_group_entry.write_text("import click\n@click.command()\ndef cli():\n pass\n", encoding="utf-8")
with pytest.raises(RuntimeError, match="click.Group"):
load_click_group("ops", bad_group_entry, "mcli.commands.bad_group.entry")
cmd_entry = tmp_path / "cmd.py"
cmd_entry.write_text("import click\n@click.command()\ndef cli():\n click.echo('ok')\n", encoding="utf-8")
cmd = load_click_command_from_entry("ops", cmd_entry, "mcli.commands.cmd.entry")
assert cmd.name == "ops"
def test_loader_nested_and_root_additional_branches(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: Help\nhidden: false\nenabled: true\nhelp_group: Commands\n", encoding="utf-8")
hidden_meta = tmp_path / "hidden_meta.yaml"
hidden_meta.write_text("short_help: Hidden\nhidden: true\nenabled: true\nhelp_group: Commands\n", encoding="utf-8")
group_entry = tmp_path / "group.py"
group_entry.write_text("import click\n@click.group()\ndef cli():\n pass\n", encoding="utf-8")
cmd_entry = tmp_path / "cmd.py"
cmd_entry.write_text("import click\n@click.command()\ndef cli():\n click.echo('ok')\n", encoding="utf-8")
nested_specs = {
"visible": CommandSpec(
name="visible",
entry_path=cmd_entry,
meta_path=meta,
import_path=["root", "visible"],
module_name="mcli.commands.root.visible.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
),
"hidden": CommandSpec(
name="hidden",
entry_path=cmd_entry,
meta_path=hidden_meta,
import_path=["root", "hidden"],
module_name="mcli.commands.root.hidden.entry",
hidden=True,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
),
}
base_group = click.Group(name="root")
nested_group = LazyNestedGroup(base_group, nested_specs)
ctx_nested = click.Context(nested_group)
formatter_nested = click.HelpFormatter()
nested_group.format_commands(ctx_nested, formatter_nested)
assert nested_group.get_command(ctx_nested, "missing") is None
commands_dir = tmp_path / "commands"
commands_dir.mkdir(parents=True, exist_ok=True)
root = RootCommand(commands_dir)
root._specs = {
"disabled": CommandGroupSpec(
help_summary="Disabled",
entry_path=group_entry,
module_name="mcli.commands.disabled.entry",
subcommands={},
hidden=False,
enabled=False,
help_group="Commands",
no_args_is_help=False,
has_meta=True,
),
"standalone": CommandGroupSpec(
help_summary="Standalone",
entry_path=cmd_entry,
module_name="mcli.commands.standalone.entry",
subcommands={},
hidden=False,
enabled=True,
help_group="Commands",
no_args_is_help=False,
has_meta=True,
),
}
assert root.list_commands(click.Context(root)) == ["disabled", "standalone"]
assert root.get_command(click.Context(root), "missing") is None
disabled_group = root.get_command(click.Context(root), "disabled")
assert disabled_group is not None
assert disabled_group.callback is not None
with pytest.raises(SystemExit):
disabled_group.callback()
standalone = root.get_command(click.Context(root), "standalone")
assert standalone is not None
formatter_root = click.HelpFormatter()
root.format_commands(click.Context(root), formatter_root)
def test_loader_nested_group_wrap_and_multi_grouping(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: Help\nhidden: false\nenabled: true\nhelp_group: Commands\n", encoding="utf-8")
entry_group = tmp_path / "group_entry.py"
entry_group.write_text("import click\n@click.group()\ndef cli():\n pass\n", encoding="utf-8")
entry_cmd = tmp_path / "cmd_entry.py"
entry_cmd.write_text("import click\n@click.command()\ndef cli():\n click.echo('ok')\n", encoding="utf-8")
child_a = CommandSpec(
name="a",
entry_path=entry_cmd,
meta_path=meta,
import_path=["root", "a"],
module_name="mcli.commands.root.a.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
)
child_b = CommandSpec(
name="b",
entry_path=entry_cmd,
meta_path=meta,
import_path=["root", "b"],
module_name="mcli.commands.root.b.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
)
group_spec = CommandSpec(
name="root",
entry_path=entry_group,
meta_path=meta,
import_path=["root"],
module_name="mcli.commands.root.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=True,
subcommands={"a": child_a, "b": child_b},
no_args_is_help=False,
)
wrapped = load_click_command(group_spec)
assert isinstance(wrapped, LazyNestedGroup)
ctx = click.Context(wrapped)
formatter = click.HelpFormatter()
wrapped.format_commands(ctx, formatter)
assert wrapped.list_commands(ctx) == ["a", "b"]
def test_loader_group_spec_without_nested_children_keeps_base_group(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: Help\nhidden: false\nenabled: true\nhelp_group: Commands\n", encoding="utf-8")
entry_group = tmp_path / "group_entry.py"
entry_group.write_text("import click\n@click.group()\ndef cli():\n pass\n", encoding="utf-8")
spec = CommandSpec(
name="root",
entry_path=entry_group,
meta_path=meta,
import_path=["root"],
module_name="mcli.commands.root.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=True,
subcommands={},
no_args_is_help=False,
)
loaded = load_click_command(spec)
assert isinstance(loaded, click.Group)
assert not isinstance(loaded, LazyNestedGroup)
def test_loader_nested_and_plugin_continue_and_existing_help_group_branches(tmp_path: Path) -> None:
meta_visible = tmp_path / "meta_visible.yaml"
meta_visible.write_text(
"short_help: Visible\nhidden: false\nenabled: true\nhelp_group: Commands\n", encoding="utf-8"
)
meta_hidden = tmp_path / "meta_hidden.yaml"
meta_hidden.write_text("short_help: Hidden\nhidden: true\nenabled: true\nhelp_group: Commands\n", encoding="utf-8")
entry_cmd = tmp_path / "cmd.py"
entry_cmd.write_text("import click\n@click.command()\ndef cli():\n click.echo('ok')\n", encoding="utf-8")