-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
2449 lines (2014 loc) · 74.4 KB
/
test_cli.py
File metadata and controls
2449 lines (2014 loc) · 74.4 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 os
import shutil
import subprocess
import sys
import logging
from pathlib import Path
import pytest
import rich_click as click
from click.testing import CliRunner
from abxpkg import EnvProvider, SemVer
import abxpkg.cli as cli_module
def _abxpkg_executable() -> Path:
"""Locate the installed abxpkg console script for subprocess-based tests."""
candidate = Path(sys.executable).parent / "abxpkg"
if candidate.exists():
return candidate
resolved = shutil.which("abxpkg")
assert resolved, "abxpkg console script must be installed in the active venv"
return Path(resolved)
def _abx_executable() -> Path:
"""Locate the installed `abx` console script for subprocess-based tests."""
candidate = Path(sys.executable).parent / "abx"
if candidate.exists():
return candidate
resolved = shutil.which("abx")
assert resolved, "abx console script must be installed in the active venv"
return Path(resolved)
def _run_cli(
script: Path,
*args: str,
env_overrides: dict[str, str] | None = None,
timeout: float = 600,
) -> subprocess.CompletedProcess[str]:
"""Invoke a console script with a clean ABXPKG_* environment."""
env = {
key: value for key, value in os.environ.items() if not key.startswith("ABXPKG_")
}
if env_overrides:
env.update(env_overrides)
return subprocess.run(
[str(script), *args],
capture_output=True,
text=True,
env=env,
timeout=timeout,
)
def _run_abxpkg_cli(
*args: str,
env_overrides: dict[str, str] | None = None,
timeout: float = 600,
) -> subprocess.CompletedProcess[str]:
"""Invoke the real `abxpkg` console script with a clean env."""
return _run_cli(
_abxpkg_executable(),
*args,
env_overrides=env_overrides,
timeout=timeout,
)
def _run_abx_cli(
*args: str,
env_overrides: dict[str, str] | None = None,
timeout: float = 600,
) -> subprocess.CompletedProcess[str]:
"""Invoke the real `abx` console script with a clean env."""
return _run_cli(
_abx_executable(),
*args,
env_overrides=env_overrides,
timeout=timeout,
)
@pytest.fixture(autouse=True)
def restore_abxpkg_logger():
package_logger = logging.getLogger("abxpkg")
original_level = package_logger.level
original_handlers = list(package_logger.handlers)
original_propagate = package_logger.propagate
try:
yield
finally:
package_logger.handlers.clear()
for handler in original_handlers:
package_logger.addHandler(handler)
package_logger.setLevel(original_level)
package_logger.propagate = original_propagate
def test_build_providers_uses_managed_lib_layout(tmp_path, monkeypatch):
monkeypatch.setenv("ABXPKG_LIB_DIR", str(tmp_path))
providers = cli_module.build_providers(
["uv", "pip", "pnpm", "cargo", "env"],
dry_run=True,
)
assert providers[0].install_root == tmp_path / "uv"
assert providers[1].install_root == tmp_path / "pip"
assert providers[2].install_root == tmp_path / "pnpm"
assert providers[3].install_root == tmp_path / "cargo"
assert providers[4].name == "env"
assert all(provider.dry_run for provider in providers)
def test_parse_provider_names_uses_preferred_default_cli_order(monkeypatch):
monkeypatch.delenv("ABXPKG_BINPROVIDERS", raising=False)
assert cli_module.parse_provider_names(None) == list(
cli_module.DEFAULT_PROVIDER_NAMES,
)
def test_default_cli_sets_managed_lib_dir(monkeypatch):
monkeypatch.delenv("ABXPKG_LIB_DIR", raising=False)
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
captured["env_lib_dir"] = os.environ.get("ABXPKG_LIB_DIR")
captured["install_root"] = cli_module.build_providers(
["pip"],
dry_run=True,
)[0].install_root
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["load", "python"],
)
assert result.exit_code == 0
assert captured["binary_name"] == "python"
assert captured["action"] == "load"
assert captured["options"].lib_dir == cli_module.DEFAULT_LIB_DIR.resolve()
assert captured["env_lib_dir"] == str(cli_module.DEFAULT_LIB_DIR.resolve())
assert captured["install_root"] == cli_module.DEFAULT_LIB_DIR.resolve() / "pip"
def test_cli_lib_none_disables_managed_mode(monkeypatch, tmp_path):
monkeypatch.setenv("ABXPKG_LIB_DIR", str(tmp_path))
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
captured["env_lib_dir"] = os.environ.get("ABXPKG_LIB_DIR")
captured["install_root"] = cli_module.build_providers(
["pip"],
dry_run=True,
)[0].install_root
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["--lib=None", "load", "python"],
)
assert result.exit_code == 0
assert captured["binary_name"] == "python"
assert captured["action"] == "load"
assert captured["options"].lib_dir == cli_module.DEFAULT_LIB_DIR.resolve()
assert captured["env_lib_dir"] is None
assert captured["install_root"] is None
def test_cli_global_flag_disables_managed_mode(monkeypatch, tmp_path):
monkeypatch.setenv("ABXPKG_LIB_DIR", str(tmp_path))
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
captured["env_lib_dir"] = os.environ.get("ABXPKG_LIB_DIR")
captured["install_root"] = cli_module.build_providers(
["pip"],
dry_run=True,
)[0].install_root
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["--global", "load", "python"],
)
assert result.exit_code == 0
assert captured["binary_name"] == "python"
assert captured["action"] == "load"
assert captured["options"].lib_dir == cli_module.DEFAULT_LIB_DIR.resolve()
assert captured["env_lib_dir"] is None
assert captured["install_root"] is None
def test_env_lib_none_disables_managed_mode(monkeypatch):
monkeypatch.setenv("ABXPKG_LIB_DIR", "None")
options = cli_module.build_cli_options(
None,
lib_dir=None,
global_mode=None,
binproviders="pip",
dry_run=None,
debug=None,
no_cache=None,
min_version=None,
postinstall_scripts=None,
min_release_age=None,
overrides=None,
install_root=None,
bin_dir=None,
euid=None,
install_timeout=None,
version_timeout=None,
)
assert options.lib_dir == cli_module.DEFAULT_LIB_DIR.resolve()
assert os.environ.get("ABXPKG_LIB_DIR") is None
assert cli_module.build_providers(["pip"], dry_run=True)[0].install_root is None
def test_install_command_uses_env_defaults(monkeypatch, tmp_path):
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["install", "prettier"],
env={
"ABXPKG_LIB_DIR": str(tmp_path),
"ABXPKG_BINPROVIDERS": "pnpm,uv",
"ABXPKG_DRY_RUN": "1",
},
)
assert result.exit_code == 0
assert captured["binary_name"] == "prettier"
assert captured["action"] == "install"
assert captured["options"].lib_dir == tmp_path.resolve()
assert captured["options"].provider_names == ["pnpm", "uv"]
assert captured["options"].dry_run is True
assert captured["options"].debug is False
assert captured["options"].no_cache is False
def test_build_cli_options_exports_resolved_provider_names(monkeypatch):
monkeypatch.delenv("ABXPKG_BINPROVIDERS", raising=False)
options = cli_module.build_cli_options(
None,
lib_dir=None,
global_mode=None,
binproviders="brew,env",
dry_run=None,
debug=None,
no_cache=None,
min_version=None,
postinstall_scripts=None,
min_release_age=None,
overrides=None,
install_root=None,
bin_dir=None,
euid=None,
install_timeout=None,
version_timeout=None,
)
assert options.provider_names == ["brew", "env"]
assert os.environ["ABXPKG_BINPROVIDERS"] == "brew,env"
def test_install_command_uses_debug_env_default(monkeypatch, tmp_path):
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["install", "prettier"],
env={
"ABXPKG_LIB_DIR": str(tmp_path),
"ABXPKG_DEBUG": "1",
},
)
assert result.exit_code == 0
assert captured["binary_name"] == "prettier"
assert captured["action"] == "install"
assert captured["options"].debug is True
def test_install_command_uses_debug_flag(monkeypatch, tmp_path):
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["--debug=True", "install", "prettier"],
env={"ABXPKG_LIB_DIR": str(tmp_path)},
)
assert result.exit_code == 0
assert captured["binary_name"] == "prettier"
assert captured["action"] == "install"
assert captured["options"].debug is True
def test_install_command_uses_no_cache_env_default(monkeypatch, tmp_path):
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["install", "prettier"],
env={
"ABXPKG_LIB_DIR": str(tmp_path),
"ABXPKG_NO_CACHE": "1",
},
)
assert result.exit_code == 0
assert captured["binary_name"] == "prettier"
assert captured["action"] == "install"
assert captured["options"].no_cache is True
def test_clear_command_removes_explicit_lib_dir(tmp_path):
(tmp_path / "pip").mkdir(parents=True)
(tmp_path / "pip" / "marker").write_text("x")
result = CliRunner().invoke(
cli_module.cli,
["clear", f"--lib={tmp_path}"],
)
assert result.exit_code == 0
assert not tmp_path.exists()
def test_clear_command_uses_env_lib_dir(tmp_path):
(tmp_path / "uv" / "venv").mkdir(parents=True)
(tmp_path / "uv" / "venv" / "marker").write_text("x")
result = CliRunner().invoke(
cli_module.cli,
["clear"],
env={"ABXPKG_LIB_DIR": str(tmp_path)},
)
assert result.exit_code == 0
assert not tmp_path.exists()
def test_version_command_with_binary_aliases_load(monkeypatch, tmp_path):
captured = {}
def fake_run_binary_command(binary_name, *, action, options):
captured["binary_name"] = binary_name
captured["action"] = action
captured["options"] = options
monkeypatch.setattr(cli_module, "run_binary_command", fake_run_binary_command)
result = CliRunner().invoke(
cli_module.cli,
["version", f"--lib={tmp_path}", "--binproviders=env", "python3"],
)
assert result.exit_code == 0
assert captured["binary_name"] == "python3"
assert captured["action"] == "load"
assert captured["options"].dry_run is False
def test_expand_bare_bool_flags_rewrites_debug_before_run():
assert cli_module._expand_bare_bool_flags(
["--debug", "run", "python3", "--debug"],
) == ["--debug=True", "run", "python3", "--debug"]
# ---------------------------------------------------------------------------
# `abxpkg run` subcommand (real live subprocess-based tests)
# ---------------------------------------------------------------------------
def test_run_executes_preinstalled_binary_via_env_provider():
"""`abxpkg run` with an already-installed binary should stream its output.
Uses ``python3`` rather than ``ls`` because BSD ``ls`` (macOS) does
not support ``--version`` / ``-version`` / ``-v``, so the env
provider can't ``load()`` it.
"""
proc = _run_abxpkg_cli(
"--binproviders=env",
"run",
"python3",
"-c",
"print('abx-run-ok')",
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip() == "abx-run-ok"
assert proc.stderr == ""
def test_run_accepts_update_flag_after_subcommand_for_env_provider():
proc = _run_abxpkg_cli(
"--binproviders=env",
"run",
"--update",
"python3",
"--version",
)
assert proc.returncode != 0
assert "Unable to update binary python3 via providers env" in proc.stderr
def test_run_accepts_binproviders_flag_after_subcommand():
proc = _run_abxpkg_cli(
"run",
"--binproviders=env",
"python3",
"--version",
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().startswith("Python "), proc.stdout
def test_version_subcommand_loads_normal_binary_via_env_provider():
proc = _run_abxpkg_cli("--binproviders=env", "version", "python3")
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().endswith(" python3"), proc.stdout
assert proc.stderr == ""
def test_version_subcommand_loads_installer_binary_via_env_provider():
proc = _run_abxpkg_cli("--binproviders=env", "version", "uv")
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().endswith(" uv"), proc.stdout
assert proc.stderr == ""
def test_run_passes_flag_args_through_without_requiring_dash_dash():
"""Flags after `run BINARY_NAME` must reach the binary, not click.
Uses ``python3 --version`` instead of ``ls --help`` because macOS ships
BSD ``ls``, which does not understand ``--help`` and exits non-zero.
"""
proc = _run_abxpkg_cli("--binproviders=env", "run", "python3", "--version")
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().startswith("Python "), proc.stdout
assert proc.stderr == ""
def test_run_propagates_nonzero_exit_code_from_underlying_binary():
"""Exit codes from the underlying binary must flow back unchanged."""
proc = _run_abxpkg_cli(
"--binproviders=env",
"run",
"python3",
"-c",
"import sys; sys.stderr.write('boom\\n'); sys.exit(7)",
)
assert proc.returncode == 7
assert proc.stdout == ""
assert "boom" in proc.stderr
def test_run_update_skips_env_for_the_update_step(monkeypatch, tmp_path):
calls: list[tuple[str, object]] = []
class FakeLoadedProvider:
def __init__(self, name: str):
self.name = name
def exec(self, bin_name, cmd=(), capture_output=False):
calls.append(
("exec", (self.name, str(bin_name), tuple(cmd), capture_output)),
)
return subprocess.CompletedProcess(
[str(bin_name), *cmd],
0,
"",
"",
)
class FakeRunBinary:
def __init__(self):
self.loaded_abspath = Path("/tmp/fake-bin")
self.loaded_version = SemVer("1.2.3")
self.loaded_binprovider = FakeLoadedProvider("env")
self.binproviders = []
self.is_valid = True
def load(self, no_cache=None):
calls.append(("load", (no_cache,)))
return self
def install(self, dry_run=None, no_cache=None):
calls.append(("install", (dry_run, no_cache)))
return self
def update(self, binproviders=None, dry_run=None, no_cache=None):
calls.append(("update", (tuple(binproviders or ()), dry_run, no_cache)))
self.loaded_binprovider = FakeLoadedProvider("brew")
return self
monkeypatch.setattr(
cli_module,
"build_binary",
lambda *args, **kwargs: FakeRunBinary(),
)
result = CliRunner().invoke(
cli_module.cli,
[
f"--lib={tmp_path}",
"--binproviders=env,brew",
"run",
"--update",
"python3",
"--version",
],
)
assert result.exit_code == 0
assert calls == [
("load", (False,)),
("update", (("brew",), False, False)),
("exec", ("brew", "/tmp/fake-bin", ("--version",), False)),
]
def test_run_stdout_stderr_are_separated_and_not_buffered(tmp_path):
"""stdout and stderr from the underlying binary must stream separately."""
# Drop a tiny shim script into a fresh PATH directory that the env
# provider will pick up. The script must respond to --version so
# EnvProvider can .load() it, then return a non-zero exit code with
# output split across stdout/stderr.
script = tmp_path / "abxpkg-run-shim"
script.write_text(
"#!/bin/sh\n"
'if [ "$1" = "--version" ]; then\n'
' echo "abxpkg-run-shim 1.2.3"\n'
" exit 0\n"
"fi\n"
"echo 'this goes to stdout'\n"
"echo 'this goes to stderr' >&2\n"
"exit 7\n",
)
script.chmod(0o755)
# Use an ad-hoc PATH that exposes the custom script as a "binary".
proc = _run_abxpkg_cli(
"--binproviders=env",
"run",
script.name,
env_overrides={"PATH": f"{tmp_path}:{os.environ['PATH']}"},
)
assert proc.returncode == 7, proc.stderr
assert proc.stdout == "this goes to stdout\n"
assert "this goes to stderr" in proc.stderr
# Nothing from abxpkg itself should leak into stdout.
assert "abxpkg" not in proc.stdout.lower()
def test_run_without_install_exits_one_when_binary_is_missing():
"""If the binary is not installed by any provider, we exit 1."""
proc = _run_abxpkg_cli(
"--binproviders=env",
"run",
"abxpkg-test-definitely-not-installed-xyz",
"--help",
)
assert proc.returncode == 1
assert proc.stdout == ""
assert "abxpkg-test-definitely-not-installed-xyz" in proc.stderr
def test_run_respects_abxpkg_binproviders_env_var():
"""The ABXPKG_BINPROVIDERS env var should restrict provider resolution."""
proc = _run_abxpkg_cli(
"run",
"python3",
"-c",
"print('from env var')",
env_overrides={"ABXPKG_BINPROVIDERS": "env"},
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip() == "from env var"
def test_run_binproviders_flag_overrides_env_var():
"""`--binproviders` on the command line wins over ABXPKG_BINPROVIDERS."""
proc = _run_abxpkg_cli(
"--binproviders=env",
"run",
"python3",
"-c",
"print('flag wins')",
env_overrides={"ABXPKG_BINPROVIDERS": "pip,brew"},
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip() == "flag wins"
def test_run_with_install_flag_installs_binary_before_executing(tmp_path):
"""`--install` should install the binary if needed, then exec."""
proc = _run_abxpkg_cli(
f"--lib={tmp_path}",
"--binproviders=pip",
"--install",
"run",
"black",
"--version",
timeout=900,
)
assert proc.returncode == 0, proc.stderr
# stdout must contain *only* black's --version output
assert proc.stdout.strip().startswith("black")
# The binary must have actually been installed under our isolated lib dir.
installed = list((tmp_path / "pip").rglob("black"))
assert installed, (
f"Expected black to be installed under {tmp_path}/pip, "
f"found nothing. stderr was:\n{proc.stderr}"
)
def test_run_with_update_flag_installs_and_updates_before_executing(tmp_path):
"""`--update` should ensure the binary is available, then update it."""
proc = _run_abxpkg_cli(
f"--lib={tmp_path}",
"--binproviders=pip",
"--update",
"run",
"black",
"--version",
timeout=900,
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().startswith("black")
installed = list((tmp_path / "pip").rglob("black"))
assert installed
def test_run_with_install_keeps_install_logs_off_stdout(tmp_path):
"""Install progress logs must go to stderr, stdout stays clean."""
proc = _run_abxpkg_cli(
f"--lib={tmp_path}",
"--binproviders=pip",
"--install",
"run",
"black",
"--version",
timeout=900,
# Force a deterministic, non-TTY log level so we can assert on it.
env_overrides={
"ABXPKG_LIB_DIR": str(tmp_path),
"ABXPKG_BINPROVIDERS": "pip",
},
)
assert proc.returncode == 0, proc.stderr
# stdout must be *only* the black --version output, nothing abxpkg-ish.
stdout_lines = proc.stdout.strip().splitlines()
assert stdout_lines
assert stdout_lines[0].startswith("black"), stdout_lines
for line in stdout_lines:
assert "Installing" not in line
assert "Loading" not in line
assert "Binary.load" not in line
def test_run_pip_subcommand_uses_pip_provider_exec(tmp_path):
"""`abxpkg --binproviders=pip run pip show X` exercises PipProvider.exec."""
# Prime a fresh pip venv so we control what's inside.
install_proc = _run_abxpkg_cli(
f"--lib={tmp_path}",
"--binproviders=pip",
"install",
"black",
timeout=900,
)
assert install_proc.returncode == 0, install_proc.stderr
proc = _run_abxpkg_cli(
f"--lib={tmp_path}",
"--binproviders=pip",
"run",
"pip",
"show",
"black",
timeout=300,
)
assert proc.returncode == 0, proc.stderr
assert "Name: black" in proc.stdout
# Ensure the pip that ran was from our isolated venv, not the system pip:
# pip show always prints a `Location:` line, so we must verify it points
# *inside* the tmp_path rather than just that the header is present.
location_lines = [
line for line in proc.stdout.splitlines() if line.startswith("Location:")
]
assert location_lines, (
f"pip show did not emit a Location line; stdout was:\n{proc.stdout}"
)
assert str(tmp_path) in location_lines[0], (
f"pip show reported {location_lines[0]!r}, which is outside the "
f"isolated venv under {tmp_path}. The `run` subcommand probably "
f"exec'd the system pip instead of the PipProvider's pip."
)
@pytest.mark.parametrize(
("extra_args", "expected_exit", "expected_stdout"),
[
(("-c", "print('zero')"), 0, "zero"),
(
("-c", "print('one'); import sys; sys.exit(0)"),
0,
"one",
),
(
("-c", "import sys; sys.exit(3)"),
3,
"",
),
],
)
def test_run_forwards_variadic_positional_args_to_binary(
extra_args,
expected_exit,
expected_stdout,
):
proc = _run_abxpkg_cli(
"--binproviders=env",
"run",
"python3",
*extra_args,
)
assert proc.returncode == expected_exit, proc.stderr
assert proc.stdout.strip() == expected_stdout
# ---------------------------------------------------------------------------
# `abx` — thin alias for `abxpkg run --install ...` (argv-rewriting wrapper)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
("argv", "expected_pre", "expected_rest"),
[
(["yt-dlp", "--help"], [], ["yt-dlp", "--help"]),
(["--update", "yt-dlp"], ["--update"], ["yt-dlp"]),
(["--upgrade", "yt-dlp"], ["--upgrade"], ["yt-dlp"]),
(
["--binproviders=env,uv,pip,apt,brew", "yt-dlp"],
["--binproviders=env,uv,pip,apt,brew"],
["yt-dlp"],
),
(
["--lib", "/tmp/abx-lib", "--dry-run", "yt-dlp", "--help"],
["--lib", "/tmp/abx-lib", "--dry-run"],
["yt-dlp", "--help"],
),
(
["--binproviders", "pip,brew", "black", "-v"],
["--binproviders", "pip,brew"],
["black", "-v"],
),
(
["--install-args", '["black==24.2.0"]', "black", "--version"],
["--install-args", '["black==24.2.0"]'],
["black", "--version"],
),
(["--version"], ["--version"], []),
([], [], []),
# POSIX `--` option terminator: the `--` itself is consumed and
# everything after it is treated as the binary name + its args,
# regardless of whether the first token looks like an option.
(["--", "yt-dlp", "--help"], [], ["yt-dlp", "--help"]),
(
["--update", "--", "--weird-binary-name", "--help"],
["--update"],
["--weird-binary-name", "--help"],
),
(
["--binproviders=env", "--", "python3", "--version"],
["--binproviders=env"],
["python3", "--version"],
),
# `--` *after* the binary name is part of the binary's argv and
# must be forwarded verbatim (not consumed by the splitter).
(
["yt-dlp", "--", "-x"],
[],
["yt-dlp", "--", "-x"],
),
],
)
def test_split_abx_argv_splits_options_from_binary(argv, expected_pre, expected_rest):
pre, rest = cli_module._split_abx_argv(argv)
assert pre == expected_pre
assert rest == expected_rest
def test_abx_accepts_dash_dash_option_terminator_before_binary():
"""`abx --binproviders=env -- python3 --version` must still work."""
proc = _run_abx_cli(
"--binproviders=env",
"--",
"python3",
"--version",
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().startswith("Python "), proc.stdout
def test_abx_auto_installs_and_runs_preinstalled_env_binary():
"""`abx BIN` on an already-present binary resolves it and execs it."""
proc = _run_abx_cli(
"--binproviders=env",
"python3",
"-c",
"print('abx-ok')",
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip() == "abx-ok"
def test_abx_passes_flag_args_through_to_underlying_binary():
"""Flags after the binary name must reach the binary, not abxpkg.
Uses ``python3 --version`` because macOS ships BSD ``ls`` which does
not recognise ``--help``.
"""
proc = _run_abx_cli("--binproviders=env", "python3", "--version")
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().startswith("Python "), proc.stdout
assert proc.stderr == ""
def test_abx_debug_does_not_probe_later_providers_before_env_resolves():
proc = _run_abx_cli(
"--debug",
"--binproviders=env,brew,apt",
"python3",
"--version",
)
assert proc.returncode == 0, proc.stderr
assert proc.stdout.strip().startswith("Python "), proc.stdout
assert (
"BinProvider.load(BrewProvider(name='brew'), bin_name='brew')"
not in proc.stderr
)
assert (
"BinProvider.load(AptProvider(name='apt'), bin_name='apt-get')"
not in proc.stderr
)
def test_abx_debug_env_provider_uses_derived_env_on_second_run(tmp_path):
first = _run_abx_cli(
"--debug",
f"--lib={tmp_path}",
"--binproviders=env",
"python3",
"--version",
)
second = _run_abx_cli(
"--debug",
f"--lib={tmp_path}",
"--binproviders=env",
"python3",
"--version",
)
assert first.returncode == 0, first.stderr
assert second.returncode == 0, second.stderr
assert "EnvProvider.get_version('python3'" in first.stderr
assert "EnvProvider.get_version('python3'" not in second.stderr
def test_list_command_reads_provider_local_derived_env(tmp_path):
provider = EnvProvider(
install_root=tmp_path / "env",
postinstall_scripts=True,
min_release_age=0,
)
loaded = provider.load("python3")
assert loaded is not None
assert loaded.loaded_version is not None
assert loaded.loaded_abspath is not None
assert provider.install_root is not None
assert (provider.install_root / "derived.env").is_file()
proc = _run_abxpkg_cli("list", f"--lib={tmp_path}", "--binproviders=env")
assert proc.returncode == 0, proc.stderr
expected_line = cli_module.format_loaded_binary_line(
loaded.loaded_version,
loaded.loaded_abspath,
"env",
"python3",
)
assert expected_line in proc.stdout.splitlines()
assert proc.stderr == ""
def test_list_command_includes_installer_binaries_by_default(tmp_path):
env_provider = EnvProvider(
install_root=tmp_path / "env",
postinstall_scripts=True,
min_release_age=0,
)
loaded = env_provider.load("python3")
uv_provider = cli_module.build_providers(
["uv"],
dry_run=False,