-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtest_cli.py
More file actions
2367 lines (2045 loc) · 77.8 KB
/
test_cli.py
File metadata and controls
2367 lines (2045 loc) · 77.8 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
"""Test CLI entry point for for vcspull."""
from __future__ import annotations
import contextlib
import importlib
import json
import logging
import pathlib
import re
import shutil
import sys
import typing as t
import pytest
import yaml
from libvcs.pytest_plugin import (
hg_remote_repo_single_commit_post_init,
skip_if_hg_missing,
skip_if_svn_missing,
svn_remote_repo_single_commit_post_init,
)
from vcspull.__about__ import __version__
from vcspull._internal.private_path import PrivatePath
from vcspull.cli import cli
from vcspull.cli._output import PlanAction, PlanEntry, PlanResult, PlanSummary
from vcspull.cli.sync import EXIT_ON_ERROR_MSG, NO_REPOS_FOR_TERM_MSG
from .helpers import write_config
sync_module = importlib.import_module("vcspull.cli.sync")
if t.TYPE_CHECKING:
from typing import TypeAlias
from libvcs.pytest_plugin import CreateRepoPytestFixtureFn
from libvcs.sync.git import GitSync
ExpectedOutput: TypeAlias = str | list[str] | None
class SyncCLINonExistentRepo(t.NamedTuple):
"""Pytest fixture for vcspull syncing when repo does not exist."""
# pytest internal: used for naming test
test_id: str
# test parameters
sync_args: list[str]
expected_exit_code: int
expected_in_out: ExpectedOutput = None
expected_not_in_out: ExpectedOutput = None
expected_in_err: ExpectedOutput = None
expected_not_in_err: ExpectedOutput = None
SYNC_CLI_EXISTENT_REPO_FIXTURES: list[SyncCLINonExistentRepo] = [
SyncCLINonExistentRepo(
test_id="exists",
sync_args=["my_git_project"],
expected_exit_code=0,
expected_in_out="Already on 'master'",
expected_not_in_out=NO_REPOS_FOR_TERM_MSG.format(name="my_git_repo"),
),
SyncCLINonExistentRepo(
test_id="non-existent-only",
sync_args=["this_isnt_in_the_config"],
expected_exit_code=0,
expected_in_out=NO_REPOS_FOR_TERM_MSG.format(name="this_isnt_in_the_config"),
),
SyncCLINonExistentRepo(
test_id="non-existent-mixed",
sync_args=["this_isnt_in_the_config", "my_git_project", "another"],
expected_exit_code=0,
expected_in_out=[
NO_REPOS_FOR_TERM_MSG.format(name="this_isnt_in_the_config"),
NO_REPOS_FOR_TERM_MSG.format(name="another"),
],
expected_not_in_out=NO_REPOS_FOR_TERM_MSG.format(name="my_git_repo"),
),
]
@pytest.mark.parametrize(
list(SyncCLINonExistentRepo._fields),
SYNC_CLI_EXISTENT_REPO_FIXTURES,
ids=[test.test_id for test in SYNC_CLI_EXISTENT_REPO_FIXTURES],
)
def test_sync_cli_filter_non_existent(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
caplog: pytest.LogCaptureFixture,
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
git_repo: GitSync,
test_id: str,
sync_args: list[str],
expected_exit_code: int,
expected_in_out: ExpectedOutput,
expected_not_in_out: ExpectedOutput,
expected_in_err: ExpectedOutput,
expected_not_in_err: ExpectedOutput,
) -> None:
"""Tests vcspull syncing when repo does not exist."""
config = {
"~/github_projects/": {
"my_git_project": {
"url": f"git+file://{git_repo.path}",
"remotes": {"test_remote": f"git+file://{git_repo.path}"},
},
},
}
yaml_config = config_path / ".vcspull.yaml"
write_config(yaml_config, yaml.dump(config, default_flow_style=False))
monkeypatch.chdir(tmp_path)
with contextlib.suppress(SystemExit):
cli(["sync", *sync_args])
captured = capsys.readouterr()
output = "".join([*caplog.messages, captured.out, captured.err])
if expected_in_out is not None:
if isinstance(expected_in_out, str):
expected_in_out = [expected_in_out]
for needle in expected_in_out:
assert needle in output
if expected_not_in_out is not None:
if isinstance(expected_not_in_out, str):
expected_not_in_out = [expected_not_in_out]
for needle in expected_not_in_out:
assert needle not in output
def test_sync_none_message_for_path_pattern(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
caplog: pytest.LogCaptureFixture,
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
git_repo: GitSync,
) -> None:
"""Path-like patterns that match no repo should show the search term, not 'None'.
When a user runs ``vcspull sync ~/nonexistent_path/``, the CLI classifies the
argument as a *path* (not a name). The ``name`` variable stays ``None``, but
the error message formats with ``name``, producing::
No repo found in config(s) for "None"
instead of::
No repo found in config(s) for "~/nonexistent_path/"
"""
config = {
"~/github_projects/": {
"my_git_project": {
"url": f"git+file://{git_repo.path}",
"remotes": {"test_remote": f"git+file://{git_repo.path}"},
},
},
}
yaml_config = config_path / ".vcspull.yaml"
write_config(yaml_config, yaml.dump(config, default_flow_style=False))
monkeypatch.chdir(tmp_path)
caplog.set_level(logging.INFO)
with contextlib.suppress(SystemExit):
cli(["sync", "~/nonexistent_path/"])
captured = capsys.readouterr()
output = "".join([*caplog.messages, captured.out, captured.err])
# The actual search term should appear in the message
assert "~/nonexistent_path/" in output
# The Python None literal should NOT appear
assert '"None"' not in output
class CLIFixture(t.NamedTuple):
"""Pytest fixture for vcspull CLI subcommands."""
# pytest internal: used for naming test
test_id: str
# test params
cli_args: list[str]
expected_exit_code: int
expected_in_out: ExpectedOutput = None
expected_not_in_out: ExpectedOutput = None
expected_in_err: ExpectedOutput = None
expected_not_in_err: ExpectedOutput = None
CLI_FIXTURES: list[CLIFixture] = [
# Empty (root command)
CLIFixture(
test_id="empty",
cli_args=[],
expected_exit_code=0,
expected_in_out=["{sync", "positional arguments:"],
),
# Version
CLIFixture(
test_id="--version",
cli_args=["--version"],
expected_exit_code=0,
expected_in_out=[__version__, ", libvcs"],
),
CLIFixture(
test_id="-V",
cli_args=["-V"],
expected_exit_code=0,
expected_in_out=[__version__, ", libvcs"],
),
# Help
CLIFixture(
test_id="--help",
cli_args=["--help"],
expected_exit_code=0,
expected_in_out=["{sync", "positional arguments:"],
),
CLIFixture(
test_id="-h",
cli_args=["-h"],
expected_exit_code=0,
expected_in_out=["{sync", "positional arguments:"],
),
# Sync: No args shows help
CLIFixture(
test_id="sync--empty",
cli_args=["sync"],
expected_exit_code=0,
expected_in_out=["--all", "--dry-run", "Synchronize VCS repositories"],
),
# Sync: --all syncs all repos
CLIFixture(
test_id="sync--all",
cli_args=["sync", "--all"],
expected_exit_code=0,
expected_in_out="my_git_repo",
),
# Sync: --all with patterns is an error
CLIFixture(
test_id="sync--all-with-patterns",
cli_args=["sync", "--all", "my_git_repo"],
expected_exit_code=2,
expected_in_err="--all cannot be combined with positional patterns",
),
# Sync: Help
CLIFixture(
test_id="sync---help",
cli_args=["sync", "--help"],
expected_exit_code=0,
expected_in_out=["filter", "--exit-on-error"],
expected_not_in_out="--version",
),
CLIFixture(
test_id="sync--h",
cli_args=["sync", "-h"],
expected_exit_code=0,
expected_in_out=["filter", "--exit-on-error"],
expected_not_in_out="--version",
),
# Sync: Repo terms
CLIFixture(
test_id="sync--one-repo-term",
cli_args=["sync", "my_git_repo"],
expected_exit_code=0,
expected_in_out="my_git_repo",
),
# Search: No args shows help
CLIFixture(
test_id="search--empty",
cli_args=["search"],
expected_exit_code=0,
expected_in_out=["search query terms", "--ignore-case"],
),
# Add: No args shows help
CLIFixture(
test_id="add--empty",
cli_args=["add"],
expected_exit_code=0,
expected_in_out=["Filesystem path", "--workspace"],
),
# Discover: No args shows help
CLIFixture(
test_id="discover--empty",
cli_args=["discover"],
expected_exit_code=0,
expected_in_out=["Directory to scan", "--recursive"],
),
# Sync: -a short flag (alias for --all)
CLIFixture(
test_id="sync--a-short-flag",
cli_args=["sync", "-a"],
expected_exit_code=0,
expected_in_out="my_git_repo",
),
# Sync: "*" pattern (equivalent to --all)
CLIFixture(
test_id="sync--star-pattern",
cli_args=["sync", "*"],
expected_exit_code=0,
expected_in_out="my_git_repo",
),
# Sync: --all --dry-run produces a plan
CLIFixture(
test_id="sync--all--dry-run",
cli_args=["sync", "--all", "--dry-run"],
expected_exit_code=0,
expected_in_out="Plan:",
),
]
class CLINegativeFixture(t.NamedTuple):
"""Fixture for CLI negative flow validation."""
test_id: str
cli_args: list[str]
scenario: t.Literal["discover-non-dict-config", "status-missing-git"]
expected_log_fragment: str | None
expected_stdout_fragment: str | None
CLI_NEGATIVE_FIXTURES: list[CLINegativeFixture] = [
CLINegativeFixture(
test_id="discover-invalid-config",
cli_args=["discover"],
scenario="discover-non-dict-config",
expected_log_fragment="not a valid YAML dictionary",
expected_stdout_fragment=None,
),
CLINegativeFixture(
test_id="status-missing-git",
cli_args=["status", "--detailed"],
scenario="status-missing-git",
expected_log_fragment=None,
expected_stdout_fragment="Summary:",
),
]
@pytest.mark.parametrize(
list(CLIFixture._fields),
CLI_FIXTURES,
ids=[test.test_id for test in CLI_FIXTURES],
)
def test_cli_subcommands(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
git_repo: GitSync,
test_id: str,
cli_args: list[str],
expected_exit_code: int,
expected_in_out: ExpectedOutput,
expected_not_in_out: ExpectedOutput,
expected_in_err: ExpectedOutput,
expected_not_in_err: ExpectedOutput,
) -> None:
"""Tests for vcspull CLI subcommands."""
config = {
"~/github_projects/": {
"my_git_repo": {
"url": f"git+file://{git_repo.path}",
"remotes": {"test_remote": f"git+file://{git_repo.path}"},
},
"broken_repo": {
"url": f"git+file://{git_repo.path}",
"remotes": {"test_remote": "git+file://non-existent-remote"},
},
},
}
yaml_config = config_path / ".vcspull.yaml"
write_config(yaml_config, yaml.dump(config, default_flow_style=False))
# Build resolved args, injecting -f for commands that need explicit config
resolved_args = list(cli_args)
if (
resolved_args
and resolved_args[0] == "sync"
and "--help" not in resolved_args
and "-h" not in resolved_args
):
# Inject config file path for sync commands to ensure test isolation
resolved_args.extend(["-f", str(yaml_config)])
# CLI can sync
exit_code = 0
try:
cli(resolved_args)
except SystemExit as exc:
exit_code = exc.code if isinstance(exc.code, int) else 0
assert exit_code == expected_exit_code
result = capsys.readouterr()
out = result.out
err = result.err
if expected_in_out is not None:
if isinstance(expected_in_out, str):
expected_in_out = [expected_in_out]
for needle in expected_in_out:
assert needle in out
if expected_not_in_out is not None:
if isinstance(expected_not_in_out, str):
expected_not_in_out = [expected_not_in_out]
for needle in expected_not_in_out:
assert needle not in out
if expected_in_err is not None:
if isinstance(expected_in_err, str):
expected_in_err = [expected_in_err]
for needle in expected_in_err:
assert needle in err
if expected_not_in_err is not None:
if isinstance(expected_not_in_err, str):
expected_not_in_err = [expected_not_in_err]
for needle in expected_not_in_err:
assert needle not in err
def test_sync_no_patterns_no_parser_warns(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Calling sync() programmatically with no patterns/--all/parser should warn."""
from vcspull.cli.sync import sync
with caplog.at_level(logging.WARNING, logger="vcspull.cli.sync"):
sync(
repo_patterns=[],
config=None,
workspace_root=None,
dry_run=False,
output_json=False,
output_ndjson=False,
color="never",
exit_on_error=False,
show_unchanged=False,
summary_only=False,
long_view=False,
relative_paths=False,
fetch=False,
offline=False,
verbosity=0,
sync_all=False,
parser=None,
)
assert any("nothing to do" in record.message for record in caplog.records)
class SyncBrokenFixture(t.NamedTuple):
"""Tests for vcspull sync when something breaks."""
# pytest internal: used for naming test
test_id: str
# test params
sync_args: list[str]
expected_exit_code: int
expected_in_out: ExpectedOutput = None
expected_not_in_out: ExpectedOutput = None
expected_in_err: ExpectedOutput = None
expected_not_in_err: ExpectedOutput = None
SYNC_BROKEN_REPO_FIXTURES: list[SyncBrokenFixture] = [
SyncBrokenFixture(
test_id="normal-checkout",
sync_args=["my_git_repo"],
expected_exit_code=0,
expected_in_out="Already on 'master'",
),
SyncBrokenFixture(
test_id="normal-checkout--exit-on-error",
sync_args=["my_git_repo", "--exit-on-error"],
expected_exit_code=0,
expected_in_out="Already on 'master'",
),
SyncBrokenFixture(
test_id="normal-checkout--x",
sync_args=["my_git_repo", "-x"],
expected_exit_code=0,
expected_in_out="Already on 'master'",
),
SyncBrokenFixture(
test_id="normal-first-broken",
sync_args=["my_git_repo_not_found", "my_git_repo"],
expected_exit_code=0,
expected_not_in_out=EXIT_ON_ERROR_MSG,
),
SyncBrokenFixture(
test_id="normal-last-broken",
sync_args=["my_git_repo", "my_git_repo_not_found"],
expected_exit_code=0,
expected_not_in_out=EXIT_ON_ERROR_MSG,
),
SyncBrokenFixture(
test_id="exit-on-error--exit-on-error-first-broken",
sync_args=["my_git_repo_not_found", "my_git_repo", "--exit-on-error"],
expected_exit_code=1,
expected_in_err=EXIT_ON_ERROR_MSG,
),
SyncBrokenFixture(
test_id="exit-on-error--x-first-broken",
sync_args=["my_git_repo_not_found", "my_git_repo", "-x"],
expected_exit_code=1,
expected_in_err=EXIT_ON_ERROR_MSG,
expected_not_in_out="master",
),
#
# Verify ordering
#
SyncBrokenFixture(
test_id="exit-on-error--exit-on-error-last-broken",
sync_args=["my_git_repo", "my_git_repo_not_found", "-x"],
expected_exit_code=1,
expected_in_out="Already on 'master'",
expected_in_err=EXIT_ON_ERROR_MSG,
),
SyncBrokenFixture(
test_id="exit-on-error--x-last-item",
sync_args=["my_git_repo", "my_git_repo_not_found", "--exit-on-error"],
expected_exit_code=1,
expected_in_out="Already on 'master'",
expected_in_err=EXIT_ON_ERROR_MSG,
),
]
@pytest.mark.parametrize(
list(SyncBrokenFixture._fields),
SYNC_BROKEN_REPO_FIXTURES,
ids=[test.test_id for test in SYNC_BROKEN_REPO_FIXTURES],
)
def test_sync_broken(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
git_repo: GitSync,
test_id: str,
sync_args: list[str],
expected_exit_code: int,
expected_in_out: ExpectedOutput,
expected_not_in_out: ExpectedOutput,
expected_in_err: ExpectedOutput,
expected_not_in_err: ExpectedOutput,
) -> None:
"""Tests for syncing in vcspull when unexpected error occurs."""
github_projects = user_path / "github_projects"
my_git_repo = github_projects / "my_git_repo"
if my_git_repo.is_dir():
shutil.rmtree(my_git_repo)
config = {
"~/github_projects/": {
"my_git_repo": {
"url": f"git+file://{git_repo.path}",
"remotes": {"test_remote": f"git+file://{git_repo.path}"},
},
"my_git_repo_not_found": {
"url": "git+file:///dev/null",
},
},
}
yaml_config = config_path / ".vcspull.yaml"
write_config(yaml_config, yaml.dump(config, default_flow_style=False))
# CLI can sync
assert isinstance(sync_args, list)
with contextlib.suppress(SystemExit):
cli(["sync", *sync_args])
result = capsys.readouterr()
out = "".join(list(result.out))
err = "".join(list(result.err))
if expected_in_out is not None:
if isinstance(expected_in_out, str):
expected_in_out = [expected_in_out]
for needle in expected_in_out:
assert needle in out
if expected_not_in_out is not None:
if isinstance(expected_not_in_out, str):
expected_not_in_out = [expected_not_in_out]
for needle in expected_not_in_out:
assert needle not in out
if expected_in_err is not None:
if isinstance(expected_in_err, str):
expected_in_err = [expected_in_err]
for needle in expected_in_err:
assert needle in err
if expected_not_in_err is not None:
if isinstance(expected_not_in_err, str):
expected_not_in_err = [expected_not_in_err]
for needle in expected_not_in_err:
assert needle not in err
class SyncErroredRepoFixture(t.NamedTuple):
"""Tests for vcspull sync when a git operation fails silently in libvcs."""
test_id: str
sync_args: list[str]
expected_in_out: ExpectedOutput = None
expected_not_in_out: ExpectedOutput = None
expected_in_err: ExpectedOutput = None
expected_not_in_err: ExpectedOutput = None
SYNC_ERRORED_REPO_FIXTURES: list[SyncErroredRepoFixture] = [
SyncErroredRepoFixture(
test_id="fetch-failure-shows-failed",
sync_args=["my_errored_repo"],
expected_in_out="Failed syncing",
expected_not_in_out="Synced my_errored_repo",
),
SyncErroredRepoFixture(
test_id="fetch-failure-exit-on-error",
sync_args=["my_errored_repo", "--exit-on-error"],
expected_in_err=EXIT_ON_ERROR_MSG,
),
SyncErroredRepoFixture(
test_id="mixed-good-and-fetch-failure",
sync_args=["my_good_repo", "my_errored_repo"],
expected_in_out=["Synced my_good_repo", "Failed syncing my_errored_repo"],
),
SyncErroredRepoFixture(
test_id="fetch-failure-summary-line",
sync_args=["my_errored_repo"],
expected_in_out=[
"Failed syncing",
"Summary:",
"1 repos",
"0 synced",
"1 failed",
],
),
SyncErroredRepoFixture(
test_id="mixed-good-and-fetch-failure-summary-line",
sync_args=["my_good_repo", "my_errored_repo"],
expected_in_out=[
"Synced my_good_repo",
"Failed syncing my_errored_repo",
"Summary:",
"2 repos",
"1 synced",
"1 failed",
],
),
]
@pytest.mark.parametrize(
list(SyncErroredRepoFixture._fields),
SYNC_ERRORED_REPO_FIXTURES,
ids=[test.test_id for test in SYNC_ERRORED_REPO_FIXTURES],
)
def test_sync_errored_repo(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
git_repo: GitSync,
test_id: str,
sync_args: list[str],
expected_in_out: ExpectedOutput,
expected_not_in_out: ExpectedOutput,
expected_in_err: ExpectedOutput,
expected_not_in_err: ExpectedOutput,
) -> None:
"""Tests for syncing in vcspull when git operations fail (e.g. fetch error).
Unlike test_sync_broken which tests repos that can't be cloned at all,
this tests repos that clone successfully but then fail on subsequent sync
due to the remote becoming unreachable. Before SyncResult, these failures
were silently swallowed and reported as successful syncs.
"""
github_projects = user_path / "github_projects"
from libvcs._internal.run import run as libvcs_run
# git_repo comes from libvcs pytest plugin — already has a valid remote
good_remote_url = f"git+file://{git_repo.path}"
# Create a bare remote for the errored repo, with an initial commit
# so that the clone + update_repo cycle succeeds on first sync.
errored_remote_dir = tmp_path / "errored_remote"
errored_remote_dir.mkdir()
libvcs_run(["git", "init", "--bare"], cwd=errored_remote_dir)
# Bootstrap the bare remote with a commit via a temporary clone
bootstrap_dir = tmp_path / "bootstrap"
libvcs_run(
["git", "clone", str(errored_remote_dir), str(bootstrap_dir)],
)
(bootstrap_dir / "initial.txt").write_text("init", encoding="utf-8")
libvcs_run(["git", "add", "initial.txt"], cwd=bootstrap_dir)
libvcs_run(["git", "commit", "-m", "initial commit"], cwd=bootstrap_dir)
libvcs_run(["git", "push", "origin", "master"], cwd=bootstrap_dir)
# Add a second commit and push so we can create a "behind" state
(bootstrap_dir / "second.txt").write_text("second", encoding="utf-8")
libvcs_run(["git", "add", "second.txt"], cwd=bootstrap_dir)
libvcs_run(["git", "commit", "-m", "second commit"], cwd=bootstrap_dir)
libvcs_run(["git", "push", "origin", "master"], cwd=bootstrap_dir)
shutil.rmtree(bootstrap_dir)
errored_remote_url = f"git+file://{errored_remote_dir}"
config: dict[str, dict[str, dict[str, t.Any]]] = {
"~/github_projects/": {
"my_good_repo": {
"url": good_remote_url,
"remotes": {"origin": good_remote_url},
},
"my_errored_repo": {
"url": errored_remote_url,
"remotes": {"origin": errored_remote_url},
},
},
}
yaml_config = config_path / ".vcspull.yaml"
write_config(yaml_config, yaml.dump(config, default_flow_style=False))
monkeypatch.chdir(tmp_path)
# First sync: clone both repos successfully
for repo_name in ("my_good_repo", "my_errored_repo"):
repo_dir = github_projects / repo_name
if repo_dir.exists():
shutil.rmtree(repo_dir)
with contextlib.suppress(SystemExit):
cli(["sync", "my_good_repo", "my_errored_repo"])
capsys.readouterr() # Discard initial sync output
# Reset the errored repo's local clone back one commit to create
# a "behind" state that will trigger a fetch on the next sync.
errored_repo_dir = github_projects / "my_errored_repo"
libvcs_run(["git", "reset", "--hard", "HEAD^"], cwd=errored_repo_dir)
# Delete the errored remote to cause fetch failure on next sync
shutil.rmtree(errored_remote_dir)
# Second sync: should show failure for errored repo
with contextlib.suppress(SystemExit):
cli(["sync", *sync_args])
result = capsys.readouterr()
out = "".join(list(result.out))
err = "".join(list(result.err))
if expected_in_out is not None:
if isinstance(expected_in_out, str):
expected_in_out = [expected_in_out]
for needle in expected_in_out:
assert needle in out, f"Expected {needle!r} in stdout: {out!r}"
if expected_not_in_out is not None:
if isinstance(expected_not_in_out, str):
expected_not_in_out = [expected_not_in_out]
for needle in expected_not_in_out:
assert needle not in out, f"Did not expect {needle!r} in stdout: {out!r}"
if expected_in_err is not None:
if isinstance(expected_in_err, str):
expected_in_err = [expected_in_err]
for needle in expected_in_err:
assert needle in err, f"Expected {needle!r} in stderr: {err!r}"
if expected_not_in_err is not None:
if isinstance(expected_not_in_err, str):
expected_not_in_err = [expected_not_in_err]
for needle in expected_not_in_err:
assert needle not in err, f"Did not expect {needle!r} in stderr: {err!r}"
class SyncRevBranchMismatchFixture(t.NamedTuple):
"""Tests for vcspull sync when git rev references a non-existent branch."""
test_id: str
sync_args: list[str]
expected_in_out: ExpectedOutput = None
expected_not_in_out: ExpectedOutput = None
expected_in_err: ExpectedOutput = None
expected_not_in_err: ExpectedOutput = None
SYNC_REV_BRANCH_MISMATCH_FIXTURES: list[SyncRevBranchMismatchFixture] = [
SyncRevBranchMismatchFixture(
test_id="rev-master-on-main-only-remote",
sync_args=["my_repo"],
expected_in_out="Failed syncing",
expected_not_in_out="Synced my_repo",
),
SyncRevBranchMismatchFixture(
test_id="rev-master-on-main-only-remote--exit-on-error",
sync_args=["my_repo", "--exit-on-error"],
expected_in_err=EXIT_ON_ERROR_MSG,
),
]
@pytest.mark.parametrize(
list(SyncRevBranchMismatchFixture._fields),
SYNC_REV_BRANCH_MISMATCH_FIXTURES,
ids=[test.test_id for test in SYNC_REV_BRANCH_MISMATCH_FIXTURES],
)
def test_sync_rev_branch_mismatch(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
test_id: str,
sync_args: list[str],
expected_in_out: ExpectedOutput,
expected_not_in_out: ExpectedOutput,
expected_in_err: ExpectedOutput,
expected_not_in_err: ExpectedOutput,
) -> None:
"""Tests for syncing when git rev references a branch that doesn't exist.
Creates a bare remote with only a 'main' branch, then configures vcspull
with rev: master. The checkout of 'master' fails because the branch
doesn't exist on the remote, exercising the checkout error path in
GitSync.update_repo().
"""
from libvcs._internal.run import run as libvcs_run
# Create a bare remote with only a 'main' branch (no 'master')
remote_dir = tmp_path / "main_only_remote"
remote_dir.mkdir()
libvcs_run(["git", "init", "--bare", "--initial-branch=main"], cwd=remote_dir)
# Bootstrap the bare remote with a commit via a temporary clone
bootstrap_dir = tmp_path / "bootstrap"
libvcs_run(["git", "clone", str(remote_dir), str(bootstrap_dir)])
(bootstrap_dir / "initial.txt").write_text("init", encoding="utf-8")
libvcs_run(["git", "add", "initial.txt"], cwd=bootstrap_dir)
libvcs_run(["git", "commit", "-m", "initial commit"], cwd=bootstrap_dir)
libvcs_run(["git", "push", "origin", "main"], cwd=bootstrap_dir)
shutil.rmtree(bootstrap_dir)
github_projects = user_path / "github_projects"
config: dict[str, dict[str, dict[str, t.Any]]] = {
"~/github_projects/": {
"my_repo": {
"url": f"git+file://{remote_dir}",
"remotes": {"origin": f"git+file://{remote_dir}"},
"rev": "master",
},
},
}
yaml_config = config_path / ".vcspull.yaml"
write_config(yaml_config, yaml.dump(config, default_flow_style=False))
monkeypatch.chdir(tmp_path)
# Clean up any prior clone
repo_dir = github_projects / "my_repo"
if repo_dir.exists():
shutil.rmtree(repo_dir)
# Single sync: clone gets 'main', then update_repo() tries
# git checkout master → fails (no such branch)
with contextlib.suppress(SystemExit):
cli(["sync", *sync_args])
result = capsys.readouterr()
out = "".join(list(result.out))
err = "".join(list(result.err))
if expected_in_out is not None:
if isinstance(expected_in_out, str):
expected_in_out = [expected_in_out]
for needle in expected_in_out:
assert needle in out, f"Expected {needle!r} in stdout: {out!r}"
if expected_not_in_out is not None:
if isinstance(expected_not_in_out, str):
expected_not_in_out = [expected_not_in_out]
for needle in expected_not_in_out:
assert needle not in out, f"Did not expect {needle!r} in stdout: {out!r}"
if expected_in_err is not None:
if isinstance(expected_in_err, str):
expected_in_err = [expected_in_err]
for needle in expected_in_err:
assert needle in err, f"Expected {needle!r} in stderr: {err!r}"
if expected_not_in_err is not None:
if isinstance(expected_not_in_err, str):
expected_not_in_err = [expected_not_in_err]
for needle in expected_not_in_err:
assert needle not in err, f"Did not expect {needle!r} in stderr: {err!r}"
def test_sync_ambiguous_branch_dir_name(
tmp_path: pathlib.Path,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
config_path: pathlib.Path,
) -> None:
"""Regression test: branch name matching a directory must not cause fatal.
When a git repo has both a local branch ``notes`` (not a remote-tracking
ref) and a directory ``notes/``, bare ``git rev-list notes`` would fail::
fatal: ambiguous argument 'notes': both revision and filename
The ``refs/heads/`` disambiguation fix in libvcs resolves this by using
``refs/heads/notes`` instead of bare ``notes`` in ``rev_list``. This
test verifies no fatal error appears and the sync succeeds cleanly.
Setup: clone from a remote that only has ``master``, then locally
create a ``notes`` branch and a ``notes/`` directory so that
``show-ref`` returns only ``refs/heads/notes`` (no remote ref).
"""
from libvcs._internal.run import run as libvcs_run
# Create a bare remote with only master
remote_dir = tmp_path / "ambiguous_remote"
remote_dir.mkdir()
libvcs_run(["git", "init", "--bare"], cwd=remote_dir)
# Bootstrap with a commit that has a notes/ directory
bootstrap_dir = tmp_path / "bootstrap"
libvcs_run(["git", "clone", str(remote_dir), str(bootstrap_dir)])
notes_dir = bootstrap_dir / "notes"
notes_dir.mkdir()
(notes_dir / "readme.txt").write_text("notes content", encoding="utf-8")
libvcs_run(["git", "add", "notes/readme.txt"], cwd=bootstrap_dir)
libvcs_run(["git", "commit", "-m", "add notes directory"], cwd=bootstrap_dir)
libvcs_run(["git", "push", "origin", "master"], cwd=bootstrap_dir)
shutil.rmtree(bootstrap_dir)
github_projects = user_path / "github_projects"
config: dict[str, dict[str, dict[str, t.Any]]] = {
"~/github_projects/": {
"ambiguous_repo": {
"url": f"git+file://{remote_dir}",
"remotes": {"origin": f"git+file://{remote_dir}"},
"rev": "notes",
},
},
}
yaml_config = config_path / ".vcspull.yaml"
write_config(yaml_config, yaml.dump(config, default_flow_style=False))
monkeypatch.chdir(tmp_path)
# Clean up any prior clone
repo_dir = github_projects / "ambiguous_repo"
if repo_dir.exists():
shutil.rmtree(repo_dir)
# First sync: clone succeeds (lands on master)
with contextlib.suppress(SystemExit):
cli(["sync", "ambiguous_repo"])
capsys.readouterr() # Discard initial sync output
# Manually create a local 'notes' branch (no remote tracking ref)
# so that show-ref won't find refs/remotes/origin/notes
libvcs_run(["git", "checkout", "-b", "notes"], cwd=repo_dir)
# Already have notes/ directory from the clone
# Second sync: with the refs/heads/ disambiguation fix in libvcs,
# rev_list uses refs/heads/notes instead of bare 'notes', avoiding
# the ambiguity with the notes/ directory.
with contextlib.suppress(SystemExit):
cli(["sync", "ambiguous_repo"])
result = capsys.readouterr()
out = result.out
combined = out + result.err
# With refs/heads/ disambiguation, the ambiguity should be resolved