-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_coverage.py
More file actions
784 lines (635 loc) · 27.1 KB
/
test_coverage.py
File metadata and controls
784 lines (635 loc) · 27.1 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
from __future__ import annotations
import os
import shutil
from pathlib import Path
import pytest
from click.testing import CliRunner
import mcli.main as main_mod
from mcli import __version__
from mcli.loader import (
CommandSpec,
LazySubGroup,
RootCommand,
_safe_name,
discover_specs,
load_click_command,
load_group_meta,
load_meta,
)
from mcli.utils.metadata import Metadata
def test_main_instantiates_root_command(monkeypatch, tmp_path: Path) -> None:
called: dict[str, object] = {}
class DummyRoot:
def __init__(
self,
commands_dir: Path,
app_context: dict | None = None,
extra_commands_dirs: list[Path] | None = None,
):
called["commands_dir"] = commands_dir
called["app_context"] = app_context
called["extra_commands_dirs"] = extra_commands_dirs
def __call__(self, prog_name: str) -> None:
called["prog_name"] = prog_name
# Mock Metadata to return test paths
class MockMetadata:
PACKAGE_ROOT_DIR = tmp_path
COMMANDS_DIR = tmp_path / "commands"
PACKAGE_NAME = "mcli"
APP_NAME = "MyCLI"
COMMAND_NAME = "mcli"
VERSION = "1.0.0"
USER_COMMANDS_DIR = tmp_path / ".mcli" / "commands"
monkeypatch.setattr(main_mod, "RootCommand", DummyRoot)
monkeypatch.setattr(main_mod, "Metadata", MockMetadata)
(tmp_path / "commands").mkdir()
main_mod.main()
assert called["prog_name"] == "mcli"
assert called["commands_dir"] == tmp_path / "commands"
assert called["extra_commands_dirs"] == [tmp_path / ".mcli" / "commands"]
def test_execute_builtin_commands_demo_add_and_sub() -> None:
commands_dir = Path(__file__).parent.parent / "src" / "mcli" / "commands"
root = RootCommand(commands_dir)
runner = CliRunner()
add = runner.invoke(root, ["samples", "add", "1", "2"])
assert add.exit_code == 0
assert add.output.strip() == "3"
sub = runner.invoke(root, ["samples", "sub", "1", "2"])
assert sub.exit_code == 0
assert sub.output.strip() == "-1"
def test_user_commands_dir_uses_package_name() -> None:
assert Metadata.USER_CONFIG_DIR.name == f".{Metadata.PACKAGE_NAME}"
def test_metadata_uses_generic_tool_section() -> None:
assert Metadata.TOOL_METADATA_SECTION == "mcli"
def test_dev_new_plugin_rejects_invalid_names(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
# Copy admin command structure to test directory
real_commands = Path(__file__).parent.parent / "src" / "mcli" / "commands"
admin_src = real_commands / "admin"
admin_dst = commands_dir / "admin"
shutil.copytree(admin_src, admin_dst)
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(root, ["admin", "new-command", "bad!name", "--short-help", "Help"])
assert result.exit_code == 2
assert "Invalid command" in result.output
def test_dev_new_plugin_rejects_existing_plugin_without_force(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
# Copy admin command structure to test directory
real_commands = Path(__file__).parent.parent / "src" / "mcli" / "commands"
admin_src = real_commands / "admin"
admin_dst = commands_dir / "admin"
shutil.copytree(admin_src, admin_dst)
existing = commands_dir / "tools" / "compute"
existing.mkdir(parents=True)
(existing / "entry.py").write_text("# existing\n", encoding="utf-8")
(existing / "meta.yaml").write_text("short_help: existing\n", encoding="utf-8")
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
["admin", "new-command", "compute", "--parent", "tools", "--short-help", "Compute command."],
)
assert result.exit_code == 2
assert "Command already exists" in result.output
def test_dev_new_plugin_force_overwrites(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
# Copy admin command structure to test directory
real_commands = Path(__file__).parent.parent / "src" / "mcli" / "commands"
admin_src = real_commands / "admin"
admin_dst = commands_dir / "admin"
shutil.copytree(admin_src, admin_dst)
existing = commands_dir / "tools" / "compute"
existing.mkdir(parents=True)
(existing / "entry.py").write_text("# existing\n", encoding="utf-8")
(existing / "meta.yaml").write_text("short_help: existing\n", encoding="utf-8")
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
[
"admin",
"new-command",
"compute",
"--parent",
"tools",
"--short-help",
"Compute command.",
"--force",
],
)
assert result.exit_code == 0
assert "meta.yaml" in result.output
assert "entry.py" in result.output
meta_text = (existing / "meta.yaml").read_text(encoding="utf-8")
assert "short_help: Compute command." in meta_text
def test_dev_new_plugin_rejects_invalid_parent_dot_notation(tmp_path: Path, monkeypatch) -> None:
commands_dir = tmp_path / "commands"
monkeypatch.setenv(Metadata.env_var("COMMANDS_DIR"), str(commands_dir))
# Copy admin command structure to test directory
real_commands = Path(__file__).parent.parent / "src" / "mcli" / "commands"
admin_src = real_commands / "admin"
admin_dst = commands_dir / "admin"
shutil.copytree(admin_src, admin_dst)
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
["admin", "new-command", "compute", "--parent", "github..repo", "--short-help", "Compute command."],
)
assert result.exit_code == 2
assert "Invalid --parent" in result.output
def test_load_meta_rejects_invalid_yaml(tmp_path: Path) -> None:
meta = tmp_path / "meta.yaml"
meta.write_text("- not-a-mapping\n", encoding="utf-8")
with pytest.raises(RuntimeError, match=r"expected mapping"):
load_meta(meta)
def test_load_meta_rejects_missing_or_empty_short_help(tmp_path: Path) -> None:
meta_missing = tmp_path / "missing.yaml"
meta_missing.write_text("{}\n", encoding="utf-8")
with pytest.raises(RuntimeError, match=r"short_help must be a non-empty string"):
load_meta(meta_missing)
meta_empty = tmp_path / "empty.yaml"
meta_empty.write_text("short_help: ''\n", encoding="utf-8")
with pytest.raises(RuntimeError, match=r"short_help must be a non-empty string"):
load_meta(meta_empty)
def test_discover_specs_reports_missing_files(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
(commands_dir / "alpha" / "bravo").mkdir(parents=True)
with pytest.raises(RuntimeError, match=r"missing entry\.py, meta\.yaml"):
discover_specs(commands_dir)
def test_safe_name_normalizes_underscores_and_discovery_uses_hyphens(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
target = commands_dir / "alpha_tools" / "run_job"
target.mkdir(parents=True)
(target / "entry.py").write_text(
"import click\n\n@click.command()\ndef cli():\n click.echo('ok')\n",
encoding="utf-8",
)
(target / "meta.yaml").write_text("shortHelp: ok\n", encoding="utf-8")
specs = discover_specs(commands_dir)
assert _safe_name("alpha_tools") == "alpha-tools"
assert "alpha-tools" in specs
assert "run-job" in specs["alpha-tools"].subcommands
def test_discover_specs_respects_recursion_depth_limit(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
bravo = commands_dir / "alpha" / "bravo"
charlie = bravo / "charlie"
charlie.mkdir(parents=True)
(bravo / "entry.py").write_text(
"import click\n\n@click.command()\ndef cli():\n click.echo('bravo')\n",
encoding="utf-8",
)
(bravo / "meta.yaml").write_text("shortHelp: Bravo\n", encoding="utf-8")
(charlie / "entry.py").write_text(
"import click\n\n@click.command()\ndef cli():\n click.echo('charlie')\n",
encoding="utf-8",
)
(charlie / "meta.yaml").write_text("shortHelp: Charlie\n", encoding="utf-8")
shallow = discover_specs(commands_dir, max_depth=1)
shallow_bravo = shallow["alpha"].subcommands["bravo"]
assert shallow_bravo.is_group is False
assert shallow_bravo.subcommands is None
deeper = discover_specs(commands_dir, max_depth=2)
deeper_bravo = deeper["alpha"].subcommands["bravo"]
assert deeper_bravo.is_group is True
assert deeper_bravo.subcommands is not None
assert "charlie" in deeper_bravo.subcommands
def test_meta_loaders_coerce_disabled_entries_to_hidden(tmp_path: Path) -> None:
command_meta = tmp_path / "command_meta.yaml"
command_meta.write_text(
"short_help: Disabled command\nhidden: false\nenabled: false\n",
encoding="utf-8",
)
command_data = load_meta(command_meta)
assert command_data["enabled"] is False
assert command_data["hidden"] is True
group_meta = tmp_path / "group_meta.yaml"
group_meta.write_text(
"short_help: Disabled group\nhidden: false\nenabled: false\n",
encoding="utf-8",
)
group_data = load_group_meta(group_meta)
assert group_data is not None
assert group_data["enabled"] is False
assert group_data["hidden"] is True
def test_lazy_subgroup_help_groups_visible_commands_in_stable_order(tmp_path: Path) -> None:
def _spec(name: str, help_group: str, hidden: bool = False) -> CommandSpec:
entry = tmp_path / f"{name}_entry.py"
meta = tmp_path / f"{name}_meta.yaml"
entry.write_text(
f"import click\n\n@click.command()\ndef cli():\n click.echo({name!r})\n",
encoding="utf-8",
)
meta.write_text("shortHelp: help\n", encoding="utf-8")
return CommandSpec(
name=name,
entry_path=entry,
meta_path=meta,
import_path=["tools", name],
module_name=f"mcli.commands.tools.{name}.entry",
hidden=hidden,
enabled=True,
help_group=help_group,
is_group=False,
subcommands=None,
no_args_is_help=False,
)
subgroup = LazySubGroup(
"tools",
{
"zulu": _spec("zulu", "Ops"),
"alpha": _spec("alpha", "Ops"),
"build": _spec("build", "Commands"),
"audit": _spec("audit", "Admin"),
"hidden": _spec("hidden", "Ops", hidden=True),
},
)
result = CliRunner().invoke(subgroup, ["--help"])
assert result.exit_code == 0
assert "hidden" not in result.output
commands_index = result.output.index("Commands:")
admin_index = result.output.index("Admin:")
ops_index = result.output.index("Ops:")
assert commands_index < admin_index < ops_index
ops_section = result.output[ops_index:]
assert " alpha" in ops_section
assert " zulu" in ops_section
assert ops_section.index(" alpha") < ops_section.index(" zulu")
def test_root_command_invoke_attaches_app_context_to_click_context(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
target = commands_dir / "tools" / "show"
target.mkdir(parents=True)
(target / "entry.py").write_text(
"\n".join(
[
"import click",
"",
"@click.command()",
"def cli():",
" root = click.get_current_context().find_root()",
" marker = root.obj.get('MARKER', 'missing') if isinstance(root.obj, dict) else 'missing'",
" click.echo(marker)",
"",
]
),
encoding="utf-8",
)
(target / "meta.yaml").write_text("shortHelp: show marker\n", encoding="utf-8")
root = RootCommand(commands_dir, app_context={"MARKER": "attached"})
result = CliRunner().invoke(root, ["tools", "show"])
assert result.exit_code == 0
assert result.output.strip() == "attached"
def test_root_version_flag_falls_back_to_package_version(tmp_path: Path) -> None:
root = RootCommand(tmp_path / "missing-commands-dir", app_context={"COMMAND_NAME": "mcli"})
result = CliRunner().invoke(root, ["--version"])
assert result.exit_code == 0
assert result.output.strip() == __version__
def test_discover_specs_ignores_pycache_dirs(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
# Should ignore __pycache__ at both command and subcommand levels.
(commands_dir / "__pycache__").mkdir(parents=True)
(commands_dir / "alpha" / "__pycache__").mkdir(parents=True)
# Valid plugin still discovered.
plugin_dir = commands_dir / "alpha" / "bravo"
plugin_dir.mkdir(parents=True)
(plugin_dir / "entry.py").write_text(
"import click\n\n@click.command()\ndef cli():\n click.echo('ok')\n",
encoding="utf-8",
)
(plugin_dir / "meta.yaml").write_text("shortHelp: ok\n", encoding="utf-8")
specs = discover_specs(commands_dir)
assert "alpha" in specs
assert "bravo" in specs["alpha"].subcommands
def test_discover_specs_ignores_dot_prefixed_dirs(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
# Dot-prefixed folders are support/scaffolding directories and not commands.
(commands_dir / ".scaffolding").mkdir(parents=True)
(commands_dir / "alpha" / ".templates").mkdir(parents=True)
plugin_dir = commands_dir / "alpha" / "bravo"
plugin_dir.mkdir(parents=True)
(plugin_dir / "entry.py").write_text(
"import click\n\n@click.command()\ndef cli():\n click.echo('ok')\n",
encoding="utf-8",
)
(plugin_dir / "meta.yaml").write_text("shortHelp: ok\n", encoding="utf-8")
specs = discover_specs(commands_dir)
assert ".scaffolding" not in specs
assert "alpha" in specs
assert "bravo" in specs["alpha"].subcommands
def test_discover_specs_reports_invalid_meta(tmp_path: Path) -> None:
commands_dir = tmp_path / "commands"
plugin_dir = commands_dir / "alpha" / "bravo"
plugin_dir.mkdir(parents=True)
(plugin_dir / "entry.py").write_text(
"import click\n\n@click.command()\ndef cli():\n click.echo('ok')\n",
encoding="utf-8",
)
(plugin_dir / "meta.yaml").write_text("[]\n", encoding="utf-8")
with pytest.raises(RuntimeError, match=r"Invalid meta\.yaml"):
discover_specs(commands_dir)
def test_load_click_command_requires_entry_file_to_exist(tmp_path: Path) -> None:
missing_entry = tmp_path / "missing" / "entry.py"
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: ok\nhidden: false\nenabled: true\n", encoding="utf-8")
spec = CommandSpec(
name="bravo",
entry_path=missing_entry,
meta_path=meta,
import_path=["alpha", "bravo"],
module_name="mcli.commands.alpha.bravo.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
)
with pytest.raises(RuntimeError, match=r"Failed to import entry\.py"):
load_click_command(spec)
def test_load_click_command_requires_cli_export_to_be_click_command(tmp_path: Path) -> None:
entry = tmp_path / "entry.py"
entry.write_text("cli = 123\n", encoding="utf-8")
meta = tmp_path / "meta.yaml"
meta.write_text("short_help: ok\nhidden: false\nenabled: true\n", encoding="utf-8")
spec = CommandSpec(
name="bravo",
entry_path=entry,
meta_path=meta,
import_path=["alpha", "bravo"],
module_name="mcli.commands.alpha.bravo.entry",
hidden=False,
enabled=True,
help_group="Commands",
is_group=False,
subcommands=None,
no_args_is_help=False,
)
with pytest.raises(RuntimeError, match=r"must export 'cli' as a click\.Command"):
load_click_command(spec)
def _write_rebrand_fixture(project_root: Path) -> Path:
commands_dir = project_root / "src" / "mcli" / "commands"
admin_src = Path(__file__).parent.parent / "src" / "mcli" / "commands" / "admin"
shutil.copytree(admin_src, commands_dir / "admin")
(project_root / "src" / "mcli" / "utils").mkdir(parents=True, exist_ok=True)
(project_root / "src" / "mcli" / "commands" / "samples").mkdir(parents=True, exist_ok=True)
(project_root / "tests").mkdir(parents=True, exist_ok=True)
(project_root / "pyproject.toml").write_text(
(
'[project]\nname = "mcli"\nversion = "1.0.0"\n\n'
'[project.scripts]\nmcli = "mcli.main:main"\n\n'
'[tool.mcli]\nenv_prefix = "MCLI_"\nname = "MyCLI"\ncli_name = "mcli"\n'
),
encoding="utf-8",
)
(project_root / "README.md").write_text(
"# MyCLI\n\nMyCLI uses `mcli` today.\nRun `mcli --help` or `mcli --help`.\nSet MCLI_COMMANDS_DIR when needed.\n",
encoding="utf-8",
)
(project_root / "src" / "mcli" / "main.py").write_text('"""Entry point for MyCLI."""\n', encoding="utf-8")
(project_root / "src" / "mcli" / "utils" / "__init__.py").write_text(
'"""Shared utilities for the MyCLI package."""\n',
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 / "src" / "mcli" / "commands" / "samples" / "entry.py").write_text(
'"""Developer SDK demonstrations for MyCLI."""\n',
encoding="utf-8",
)
(project_root / "tests" / "test_coverage.py").write_text(
"\n".join(
[
"class MockMetadata:",
' PACKAGE_NAME = "mcli"',
' APP_NAME = "MyCLI"',
' COMMAND_NAME = "mcli"',
"",
'assert "MyCLI" == "MyCLI"',
'assert "mcli" == "mcli"',
"",
]
),
encoding="utf-8",
)
(project_root / "tests" / "test_cli.py").write_text(
"\n".join(
[
"from pathlib import Path",
"",
'USER_COMMANDS_DIR = Path.home() / ".mcli" / "commands"',
'CLI_NAME = "mcli"',
'APP_NAME = "MyCLI"',
"",
]
),
encoding="utf-8",
)
(project_root / "tests" / "test_safesettimgs.py").write_text(
'_ROOT = {"COMMAND_NAME": "mcli", "PACKAGE_NAME": "mcli", "APP_NAME": "MyCLI"}\n',
encoding="utf-8",
)
return commands_dir
def _set_test_home(monkeypatch, tmp_path: Path) -> Path:
home_dir = tmp_path / "home"
home_dir.mkdir()
monkeypatch.setenv("HOME", str(home_dir))
return home_dir
def test_admin_rebrand_updates_branding_files(tmp_path: Path, monkeypatch) -> None:
commands_dir = _write_rebrand_fixture(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
["admin", "rebrand", "--name", "Acme CLI", "--cli-cmd", "acme", "--skip-user", "--confirm"],
)
assert result.exit_code == 0
assert "Display name: MyCLI -> Acme CLI" in result.output
assert "CLI command: mcli -> acme" in result.output
assert "Package name: mcli -> acme" in result.output
assert "Env prefix: MCLI_ -> ACME_" in result.output
assert "tests/test_cli.py" in result.output
assert "tests/test_safesettimgs.py" in result.output
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")
readme_text = (tmp_path / "README.md").read_text(encoding="utf-8")
admin_entry_text = (tmp_path / "src" / "mcli" / "commands" / "admin" / "entry.py").read_text(encoding="utf-8")
admin_meta_text = (tmp_path / "src" / "mcli" / "commands" / "admin" / "meta.yaml").read_text(encoding="utf-8")
new_command_text = (tmp_path / "src" / "mcli" / "commands" / "admin" / "new_command" / "entry.py").read_text(
encoding="utf-8"
)
samples_entry_text = (tmp_path / "src" / "mcli" / "commands" / "samples" / "entry.py").read_text(encoding="utf-8")
coverage_test_text = (tmp_path / "tests" / "test_coverage.py").read_text(encoding="utf-8")
cli_test_text = (tmp_path / "tests" / "test_cli.py").read_text(encoding="utf-8")
safesettings_test_text = (tmp_path / "tests" / "test_safesettimgs.py").read_text(encoding="utf-8")
assert 'name = "acme"' in pyproject_text
assert 'acme = "mcli.main:main"' in pyproject_text
assert "[tool.mcli]" in pyproject_text
assert 'env_prefix = "ACME_"' in pyproject_text
assert 'cli_name = "acme"' in pyproject_text
assert 'name = "Acme CLI"' in pyproject_text
assert 'PACKAGE_NAME = "acme"' in metadata_text
assert 'APP_NAME = "Acme CLI"' in metadata_text
assert 'COMMAND_NAME = "acme"' in metadata_text
assert "# acme" in readme_text
assert "Acme CLI uses `acme` today." in readme_text
assert "ACME_COMMANDS_DIR" in readme_text
assert "Metadata.APP_NAME" in admin_entry_text
assert "Administrative commands" in admin_meta_text
assert "CLI_NAME = Metadata.COMMAND_NAME" in new_command_text
assert '"""Developer SDK demonstrations for Acme CLI."""' in samples_entry_text
assert 'APP_NAME = "Acme CLI"' in coverage_test_text
assert 'PACKAGE_NAME = "acme"' in coverage_test_text
assert 'COMMAND_NAME = "acme"' in coverage_test_text
assert '".acme"' in cli_test_text
assert '"acme"' in cli_test_text
assert '"Acme CLI"' in cli_test_text
assert '"COMMAND_NAME": "acme"' in safesettings_test_text
assert '"PACKAGE_NAME": "acme"' in safesettings_test_text
assert '"APP_NAME": "Acme CLI"' in safesettings_test_text
def test_admin_rebrand_requires_confirmation_without_flag(tmp_path: Path, monkeypatch) -> None:
commands_dir = _write_rebrand_fixture(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
["admin", "rebrand", "--name", "Acme CLI", "--cli-cmd", "acme", "--skip-user"],
input="n\n",
)
assert result.exit_code != 0
assert "Display name: MyCLI -> Acme CLI" in result.output
assert "Apply these changes?" in result.output
assert 'name = "mcli"' in (tmp_path / "pyproject.toml").read_text(encoding="utf-8")
def test_admin_rebrand_renames_user_config_dir_by_default(tmp_path: Path, monkeypatch) -> None:
commands_dir = _write_rebrand_fixture(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
home_dir = _set_test_home(monkeypatch, tmp_path)
old_user_dir = home_dir / ".mcli"
new_user_dir = home_dir / ".acme"
user_command = old_user_dir / "commands" / "tools" / "entry.py"
user_command.parent.mkdir(parents=True, exist_ok=True)
user_command.write_text("print('ok')\n", encoding="utf-8")
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
[
"admin",
"rebrand",
"--name",
"Acme CLI",
"--cli-cmd",
"acme",
"--confirm",
],
)
assert result.exit_code == 0
display_old_user_dir = f"~/{old_user_dir.name}"
display_new_user_dir = f"~/{new_user_dir.name}"
assert f"User config dir: {display_old_user_dir} -> {display_new_user_dir}" in result.output
assert f"{display_old_user_dir} -> {display_new_user_dir}" in result.output
assert not old_user_dir.exists()
assert (new_user_dir / "commands" / "tools" / "entry.py").read_text(encoding="utf-8") == "print('ok')\n"
def test_admin_rebrand_skips_user_config_dir_when_requested(tmp_path: Path, monkeypatch) -> None:
commands_dir = _write_rebrand_fixture(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
home_dir = _set_test_home(monkeypatch, tmp_path)
old_user_dir = home_dir / ".mcli"
new_user_dir = home_dir / ".acme"
user_command = old_user_dir / "commands" / "tools" / "entry.py"
user_command.parent.mkdir(parents=True, exist_ok=True)
user_command.write_text("print('ok')\n", encoding="utf-8")
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
[
"admin",
"rebrand",
"--name",
"Acme CLI",
"--cli-cmd",
"acme",
"--skip-user",
"--confirm",
],
)
assert result.exit_code == 0
assert "User config dir:" not in result.output
assert old_user_dir.exists()
assert not new_user_dir.exists()
assert user_command.read_text(encoding="utf-8") == "print('ok')\n"
def test_admin_rebrand_aborts_if_user_config_target_exists(tmp_path: Path, monkeypatch) -> None:
commands_dir = _write_rebrand_fixture(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
home_dir = _set_test_home(monkeypatch, tmp_path)
old_user_dir = home_dir / ".mcli"
new_user_dir = home_dir / ".acme"
old_user_dir.mkdir()
new_user_dir.mkdir()
original_pyproject = (tmp_path / "pyproject.toml").read_text(encoding="utf-8")
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
[
"admin",
"rebrand",
"--name",
"Acme CLI",
"--cli-cmd",
"acme",
"--confirm",
],
)
assert result.exit_code != 0
assert "target already exists" in result.output
assert (tmp_path / "pyproject.toml").read_text(encoding="utf-8") == original_pyproject
assert old_user_dir.exists()
assert new_user_dir.exists()
def test_admin_rebrand_aborts_if_user_config_rename_permission_check_fails(tmp_path: Path, monkeypatch) -> None:
commands_dir = _write_rebrand_fixture(tmp_path)
monkeypatch.setenv(Metadata.env_var("REBRAND_PROJECT_ROOT"), str(tmp_path))
home_dir = _set_test_home(monkeypatch, tmp_path)
old_user_dir = home_dir / ".mcli"
old_user_dir.mkdir()
original_pyproject = (tmp_path / "pyproject.toml").read_text(encoding="utf-8")
original_access = os.access
monkeypatch.setattr(
os,
"access",
lambda path, mode: False if Path(path) == home_dir else original_access(path, mode),
)
root = RootCommand(commands_dir)
runner = CliRunner()
result = runner.invoke(
root,
[
"admin",
"rebrand",
"--name",
"Acme CLI",
"--cli-cmd",
"acme",
"--confirm",
],
)
assert result.exit_code != 0
assert "insufficient permissions" in result.output
assert (tmp_path / "pyproject.toml").read_text(encoding="utf-8") == original_pyproject
assert old_user_dir.exists()
assert not (home_dir / ".acme").exists()