-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_bundle_tests.py
More file actions
2586 lines (1893 loc) · 90.1 KB
/
backup_bundle_tests.py
File metadata and controls
2586 lines (1893 loc) · 90.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
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
# backup_bundle.py: incremental backup of git repositories based on git bundle
# Copyright (C) 2025-2026 Thomas Schaap
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later
# ruff: noqa: G004, S101, S404, S603, S607, S311 # This is testing code
"""
Tests for backup_bundle.py.
"""
from __future__ import annotations
import argparse
import os
import random
import subprocess
import sys
from contextlib import contextmanager, nullcontext, suppress
from logging import getLogger
from pathlib import Path
from shutil import copy
from string import ascii_letters
from tempfile import TemporaryDirectory
from time import sleep
from typing import TYPE_CHECKING, Final
import pytest
if TYPE_CHECKING:
from collections.abc import Callable, Generator
# Import the module under test using a bit of a hack so we don't need any package infrastructure. This keeps bundle.py
# a plain single-file python script. This is done last to prevent any other files in the current directory from
# interfering with the previous imports, and to isolate the hack from the rest of the imports.
this_path = str(Path().absolute())
sys.path.append(this_path)
from backup_bundle import ( # noqa: E402
GitCallFailedError,
GitRef,
MissingRemoteError,
NoBundlesRestoredError,
SimpleLockFileNotCreatedError,
configure_logging,
get_current_branch,
is_bare_repo,
list_references_in_repo,
simple_lock_file,
)
from backup_bundle import main as _main # noqa: E402
sys.path.remove(this_path)
DEFAULT_ENVIRONMENT = {
"GIT_AUTHOR_NAME": "A U Thor",
"GIT_AUTHOR_EMAIL": "author@example.com",
"GIT_COMMITTER_NAME": "C Ommitter",
"GIT_COMMITTER_EMAIL": "committer@example.com",
}
"""A default environment for calling git with. This prevents interference from missing git config."""
UTF8 = "utf-8"
log = getLogger(__name__)
# ####################################
# ##### #####
# ##### GENERIC TEST HELPERS #####
# ##### #####
# ####################################
# These helper functions make the tests a lot easier to read and write. Lots of specialized git calls here, but also
# generic testing stuff like always changing to a temporary directory.
@contextmanager
def in_dir(directory: Path) -> Generator[None, None, None]:
"""
Change the directory to the given path in the context.
:param dir: The directory to change to.
"""
current = Path.cwd()
os.chdir(directory)
try:
yield
finally:
os.chdir(current)
@pytest.fixture(autouse=True)
def in_tmp_path(tmp_path: Path) -> Generator[Path, None, None]:
"""
Change directory to a temporary path.
:param tmp_path: A temporary directory provided by pytest
:yields: The absolute temporary path.
"""
with in_dir(tmp_path):
yield tmp_path
@pytest.fixture(scope="session", autouse=True)
def configure_bundle_logging() -> None:
"""
Configure the logging for bundle.
The logger for bundle is only created after it has been configured, which is after main has been called. Before that
time, however, that logger is indirectly called from the tests. Provide early configuration to fix that.
"""
configure_logging(
argparse.Namespace(
verbose=True,
log_config_file=None,
log_config=None,
)
)
# ###################################
# ##### #####
# ##### GIT RELATED HELPERS #####
# ##### #####
# ###################################
# These helper functions make the tests a lot easier to read and write. Also includes a reimplementation of `call_git`
# and friends, to pass an environment (in particular for `git commit`).
def backup_bundle_main(*args: str | Path) -> None:
"""
Call bundle.py main, with all arguments converted to strings.
:param args: The parameters to pass to main.
"""
_main([*[str(arg) for arg in args], "-v"])
def _call_git(arguments: list[str], *, cwd: Path) -> list[str]:
"""
Run a git process and return it's output. Internal helper without error handling.
:param arguments: The arguments to call git with (e.g. `["status"]` to call `git status`)
:param cwd: The working directory from which to call git.
"""
log.debug(f"Calling: git {' '.join(arguments)}")
process = subprocess.run(
["git", *arguments], cwd=str(cwd), capture_output=True, check=True, text=True, env=DEFAULT_ENVIRONMENT
)
return process.stdout.splitlines()
def call_git(arguments: list[str], *, cwd: Path) -> list[str]:
"""
Run a git process and return it's output.
:param arguments: The arguments to call git with (e.g. `["status"]` to call `git status`)
:param cwd: The working directory from which to call git.
"""
try:
return _call_git(arguments, cwd=cwd)
except subprocess.CalledProcessError as exc:
log.debug(f"Call failed. stdout={exc.stdout}, stderr={exc.stderr}")
raise
def try_call_git(arguments: list[str], *, cwd: Path) -> list[str]:
"""
Run a git process and return it's output, or an empty list if the command fails.
Use this call for commands that may fail (e.g. rev-parse for a revision that may or may not resolve).
:param arguments: The arguments to call git with (e.g. `["status"]` to call `git status`)
:param cwd: The working directory from which to call git.
"""
try:
return _call_git(arguments, cwd=cwd)
except subprocess.CalledProcessError:
return []
_default_branch_no_really_call_the_function_instead: str | None = None
"""
The name of the default branch to use in test repositories.
DO NOT USE! Call `default_branch()`, instead.
"""
def default_branch() -> str:
"""
The name of the default branch to use in test repositories.
Do not call before the session has been initialized! In particular, if you need this in parameterizations you should
provide indirection, for example by passing in a lambda that call this function, instead.
"""
assert _default_branch_no_really_call_the_function_instead is not None, (
"Do not call upon default_branch() before the session has been initialized."
)
return _default_branch_no_really_call_the_function_instead
@pytest.fixture(scope="session", autouse=True)
def determine_default_branch() -> str:
"""
Fixture to determine the default branch of new git repositories.
This will initialize `default_branch()`.
:yields: The name of the default branch.
"""
global _default_branch_no_really_call_the_function_instead # noqa: PLW0603
# The only reliable way to figure this out is by creating a new repository.
with TemporaryDirectory() as tmp:
branch_name, _ = get_current_branch(create_repo(tmp))
assert branch_name
_default_branch_no_really_call_the_function_instead = branch_name
return branch_name
def assert_repos_equal(repo1: Path, repo2: Path, *, include_head: bool = True) -> None:
"""
Assert that two repositories contains the same references and reachable commits for those references.
Bundle files are not supported.
If HEAD is included in the comparison, an additional check is done to verify that HEAD is the same symbolic
reference in both repositories (or detached in both).
:param repo1: The one repo to check.
:param repo2: The other repo to check.
:param include_head: Whether to compare HEAD, as well. Set to False for those cases where the HEAD is not expected
to be the same in the two repositories.
"""
assert repo1.resolve() != repo2.resolve(), "You probably meant to compare two *different* repos."
refs1 = list_references_in_repo(repo1)
refs2 = list_references_in_repo(repo2)
if not include_head:
refs1 = [ref for ref in refs1 if ref.ref != "HEAD"]
refs2 = [ref for ref in refs2 if ref.ref != "HEAD"]
assert set(refs1) == set(refs2)
for ref in refs1:
assert call_git(["rev-list", ref.ref], cwd=repo1) == call_git(["rev-list", ref.ref], cwd=repo2)
if include_head:
assert try_call_git(["symbolic-ref", "HEAD"], cwd=repo1) == try_call_git(["symbolic-ref", "HEAD"], cwd=repo2)
def assert_repos_not_equal(repo1: Path, repo2: Path) -> None:
"""
Assert that two repositories do not contains the same references and/or reachable commits for those references.
Bundle files are not supported.
:param repo1: The one repo to check.
:param repo2: The other repo to check.
"""
assert repo1.resolve() != repo2.resolve(), "You probably meant to compare two *different* repos."
refs1 = list_references_in_repo(repo1)
refs2 = list_references_in_repo(repo2)
if set(refs1) != set(refs2):
return
for ref in refs1:
if call_git(["rev-list", ref.ref], cwd=repo1) != call_git(["rev-list", ref.ref], cwd=repo2):
return
# Assert the references again. This gives the clearest output.
assert set(refs1) != set(refs2)
def create_repo(
repo: Path | str,
*,
clone: Path | str | None = None,
bare: bool = False,
mirror: bool = False,
initial_branch: str | None = None,
) -> Path:
"""
Create a git repository in repo.
:param repo: Location of the new repository.
:param clone: If set, clone from this source.
:param bare: Create a bare repository.
:param mirror: Create a mirrored clone.
:param initial_branch: If set, the name of the initial branch of the repository.
:returns: `repo`
"""
if isinstance(repo, str):
repo = Path(repo)
if isinstance(clone, str):
clone = Path(clone)
repo.mkdir(parents=True, exist_ok=True)
options: list[str] = []
if clone is not None:
assert initial_branch is None, "initial_branch makes no sense if cloning"
if mirror:
options = ["--mirror"]
elif bare:
options = ["--bare"]
call_git(["clone", *options, str(clone.absolute()), "."], cwd=repo)
else:
assert not mirror, "mirror makes no sense if not cloning"
if bare:
options = ["--bare"]
if initial_branch:
options += ["--initial-branch", initial_branch]
call_git(["init", *options, "."], cwd=repo)
return repo
def add_commits(repo: Path, branch: str | None = None, *, count: int = 1, filename: str = "random_file") -> None:
"""
Create commits on a repo.
Each commit will overwrite the same file with a random string of the same length.
:param repo: The repo to commit on.
:param branch: The branch to create commits on. Defaults to `default_branch()`.
:param count: The number of commits to add.
:param filename: The name of the file that will be updated in every commit.
"""
assert not is_bare_repo(repo), "Can't create commits on bare repo"
assert count >= 0
branch = branch or default_branch()
# Detect an empty repository (= default branch, no commits yet). Otherwise switch to the requested branch.
if branch != default_branch() or try_call_git(["rev-parse", default_branch()], cwd=repo):
call_git(["switch", "--no-guess", branch], cwd=repo)
# Create the commits
with in_dir(repo):
file = Path(filename)
for _ in range(count):
# Ensure we have some data to commit
current = file.read_text(encoding=UTF8) if file.exists() else ""
new = current
while new == current:
new = "".join(random.choices(ascii_letters, k=16))
file.write_text(new, encoding=UTF8)
# Create the commit
call_git(["add", str(file)], cwd=Path())
call_git(["commit", "-m", "Another commit"], cwd=Path())
def switch_branch(repo: Path, branch: str) -> str:
"""
Switch to the named branch in a repository.
:param repo: The repo to switch branches in.
:param branch: The name of the branch to switch to.
:returns: `branch`
"""
call_git(["switch", branch], cwd=repo)
return branch
def create_branch(repo: Path, branch: str, *, commit: str | None = None) -> str:
"""
Create a new branch on a repository.
:param repo: The repo to add a branch in.
:param branch: The name of the branch to create.
:param commit: Start the new branch from this commit. Defaults to `default_branch()`.
:returns: `branch`
"""
commit = commit or default_branch()
call_git(["branch", branch, commit], cwd=repo)
return branch
def change_branch(repo: Path, branch: str, *, new_commit: str) -> None:
"""
Change an existing branch from a repository.
:param repo: The repo to change the branch in.
:param branch: The branch to change.
:param new_commit: The new commit to point the branch to.
"""
call_git(["branch", "--force", branch, new_commit], cwd=repo)
def delete_branch(repo: Path, branch: str) -> None:
"""
Change an existing branch from a repository.
:param repo: The repo to change the branch in.
:param branch: The branch to change.
"""
call_git(["switch", "--detach", call_git(["rev-parse", branch], cwd=repo)[0]], cwd=repo)
call_git(["branch", "--delete", "--force", branch], cwd=repo)
def create_tag(repo: Path, tag: str, commit: str) -> str:
"""
Create a new tag on a repository.
:param repo: The repo to add the tag to.
:param tag: The name of the tag to create.
:param commit: The commit to tag.
:returns: `tag`
"""
call_git(["tag", "--no-sign", tag, commit], cwd=repo)
return tag
def find_reference_in_repo(repo: Path, reference: str) -> GitRef:
"""
List the named reference in a (remote) repository.
The reference must exist.
:param repo: The repository that the reference is in.
:param reference: The full name of the reference.
:return: The reference.
"""
return next(ref for ref in list_references_in_repo(repo) if ref.ref == reference)
def bundle_verifies(repo: Path, bundle: Path) -> bool:
"""
Check whether the bundle verifies for a repository.
:param repo: The repository to check in.
:param bundle: The bundle file to check.
:returns: True iff the bundle can be restored according to `git bundle verify`.
"""
try:
call_git(["bundle", "verify", str(bundle.absolute())], cwd=repo)
except subprocess.CalledProcessError:
return False
else:
return True
def list_reference_names_in_repo(repo: Path) -> set[str]:
"""
List the full reference names of all references in a repository.
This function can handle bundles.
:param repo: The repository to list.
"""
return {ref.ref for ref in list_references_in_repo(repo)}
# ##########################
# ##### #####
# ##### UNIT TESTS #####
# ##### #####
# ##########################
# Some functions of bundle aren't covered with full certainty by the rest of the tests. Their corner cases are covered
# in these unit tests.
def test_unit_get_current_branch() -> None:
"""
Verify that get_current_branch returns the expected results.
"""
repo = create_repo("repo")
bare_repo = create_repo("bare", clone=repo, bare=True, mirror=True)
# A new repository returns only the name of the default branch
assert (default_branch(), None) == get_current_branch(repo)
assert (default_branch(), None) == get_current_branch(bare_repo)
add_commits(repo)
call_git(["remote", "update"], cwd=bare_repo)
# A normal checkout returns the name of the branch and the checked out commit
branch, ref = get_current_branch(repo)
assert branch == default_branch()
assert ref is not None
assert ref.ref == f"refs/heads/{default_branch()}"
branch, ref = get_current_branch(bare_repo)
assert branch == default_branch()
assert ref is not None
assert ref.ref == f"refs/heads/{default_branch()}"
# Switch to a detached head (the update-ref is the plumbing way to do the same in a bare repo)
call_git(["switch", "--detach"], cwd=repo)
call_git(["update-ref", "--no-deref", "HEAD", ref.hash], cwd=bare_repo)
# A detached head returns only an empty string
assert get_current_branch(repo) == ("", None)
assert get_current_branch(bare_repo) == ("", None)
def test_unit_simple_lock_file() -> None:
"""
Verify that the simple_lock_file context manager works.
"""
lock_file = Path("the_lock")
# Basic lock scenario
assert not lock_file.exists()
with simple_lock_file(lock_file):
assert lock_file.exists()
assert not lock_file.exists()
# File already exists (lock fails)
lock_file.write_text("", encoding=UTF8)
assert lock_file.exists()
with pytest.raises(SimpleLockFileNotCreatedError): # noqa: SIM117 # This is more obvious to the reader
with simple_lock_file(lock_file):
pytest.fail("Should not be reached")
assert lock_file.exists()
lock_file.unlink()
# Lock-in-lock scenarion (inner lock fails)
assert not lock_file.exists()
with simple_lock_file(lock_file):
with pytest.raises(SimpleLockFileNotCreatedError): # noqa: SIM117 # This is more obvious to the reader
with simple_lock_file(lock_file):
pytest.fail("Should not be reached")
assert lock_file.exists()
assert not lock_file.exists()
# ############################
# ##### #####
# ##### BACKUP TESTS #####
# ##### #####
# ############################
# These tests focus on the creation of backups. Restores are mainly done to verify the correctness of the backup.
def test_create_full() -> None:
"""
Verify that a basic full backup and restore succeeds.
Also verifies that backing up from a normal repo works.
Also verifies that backing up to a new bundle works.
"""
bundle = Path("bundle.bundle")
metadata = Path("metadata.json")
target = Path("target")
assert not bundle.exists()
origin = create_repo("origin", bare=False)
add_commits(origin, count=3)
b1 = create_branch(origin, "b1", commit=f"{default_branch()}~2")
add_commits(origin, b1, count=4)
b2 = create_branch(origin, "b2")
add_commits(origin, b2, count=2)
create_tag(origin, "tag", "b1~1")
# Create the full backup
backup_bundle_main("create", origin, bundle, "--metadata", metadata)
# Backup was created
assert bundle.exists()
backup_bundle_main("restore", target, bundle, "--force")
# Full restore succeeded
switch_branch(origin, default_branch())
assert_repos_equal(origin, target)
def test_create_incremental() -> None:
"""
Verify that an incremental backup and restore succeeds, and is in fact incremental.
Also verifies that incremental backups against a previous bundle in a different location work.
"""
bundles = [Path("bundle1.bundle"), Path("bundle2.bundle")]
moved_bundle = Path("previous_bundle1.bundle")
previous_bundle = Path("previous.bundle")
origin = create_repo("origin")
add_commits(origin, count=2)
target = create_repo("target", bare=True)
backup_bundle_main("create", origin, bundles[0], "--previous-bundle-location", previous_bundle)
# Move the original backup bundle, so we are certain it can't be used as reference for the incremental. The previous
# bundle location should be used.
bundles[0] = bundles[0].rename(moved_bundle)
add_commits(origin, count=1)
# Create the incremental backup
backup_bundle_main("create", origin, bundles[1], "--previous-bundle-location", previous_bundle)
# The second bundle is an incremental backup (based on `git bundle verify`'s verdict)
assert bundle_verifies(target, bundles[0])
assert not bundle_verifies(target, bundles[1])
backup_bundle_main("restore", target, bundles[0])
# Restoring the first bundle is not a full restore, but sufficient to restore the incremental bundle afterwards
assert_repos_not_equal(origin, target)
assert bundle_verifies(target, bundles[0])
assert bundle_verifies(target, bundles[1])
backup_bundle_main("restore", target, bundles[1], "--force")
# Incremental restore succeeded
assert_repos_equal(origin, target)
def test_create_includes_unchanged_references() -> None:
"""
Verify that references that have no changes at all are still included in an incremental backup.
"""
bundles = [Path("bundle1.bundle"), Path("bundle2.bundle")]
previous_bundle = Path("previous.bundle")
origin = create_repo("origin")
add_commits(origin, count=2)
b1 = create_branch(origin, "b1", commit=f"{default_branch()}~1")
add_commits(origin, b1, count=10)
create_branch(origin, "b2", commit=f"{b1}~7")
target = create_repo("target", bare=True)
backup_bundle_main("create", origin, bundles[0], "--previous-bundle-location", previous_bundle)
# Note that the new commits are made on the default branch, so b1, b2 and le_tag are not reachable from them
add_commits(origin, count=2)
backup_bundle_main("create", origin, bundles[1], "--previous-bundle-location", previous_bundle)
# All references are mentioned in both bundles
assert list_reference_names_in_repo(bundles[0]) == list_reference_names_in_repo(bundles[1])
backup_bundle_main("restore", target, bundles[0])
backup_bundle_main("restore", target, bundles[1], "--force")
# Incremental restore succeeds and keeps all references
assert_repos_equal(origin, target)
TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS: Final[int] = 8
"""
The total number of commits used for test_create_reference_inclusions_and_exclusions.
This must be an even number. It does not include the first commit to ensure that the incremental backup in the test
can't accidentally be a full backup.
Please be warned that increasing this number greatly increases the number of tests.
"""
def _generate_distances() -> Generator[tuple[int, int, int], None, None]:
"""
Generate the distances for test_create_reference_inclusions_and_exclusions.
"""
for distance1 in range(TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS):
for distance2 in range(TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS - distance1):
for distance3 in range(TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS - (distance1 + distance2)):
yield (distance1, distance2, distance3)
@pytest.mark.parametrize(
("distance1", "distance2", "distance3"),
list(_generate_distances()),
# Because it's impractical to find all corner cases, a whole string of tests is attempted. For this, git repos with
# a history like below are created, with the branches' locations parameterised by their distance from the previous
# one (or the default branch):
#
# commit 8B8B (HEAD, main) --\
# commit 7777 |-> distance1 (= 2)
# commit 6666 (b1) --/ --\
# commit 5555 |-> distance2 (= 3)
# commit 4F4F |
# commit 3333 (b2) --\ --/
# commit 2222 (b3) --/-> distance3 (= 1)
# commit 1111
# commit 0000
#
# First commits 1111 - 4F4F are created, and any branches that would end up there. A first backup is created there.
# Then the rest of the commits and branches is created, and an incremental backup is created. By parameterizing the
# location of the branches, they might (among other unforeseen corner cases):
# - overlap
# - be on consecutive commits
# - be in the first full backup
# - be in the incremental backup
# - be on or around the border between the two backups
#
# The number of commits is chosen such that two branches fit entirely inside the first or the second backup, without
# them being on consecutive commits and without interacting with the commit where the initial backup is made (4F4F).
# On top of that one additional commit it added in the beginning (0000). This ensures that, no matter where the
# branches end up, the second bundle can't contain all commits in the repo. This way we can verify that it is indeed
# an incremental backup by attempting `git bundle verify` against an empty repo (which should hence fail).
)
def test_create_reference_inclusions_and_exclusions(distance1: int, distance2: int, distance3: int) -> None:
"""
Verify that the inclusion/exclusion selection correctly includes all references, no matter their relative distances.
"""
def add_branch(name: str, current_commit_count: int, branch_distance: int, *, already_added: bool) -> bool:
"""
Add a branch to the origin repository, if its intended commit exists.
:param name: Name of the branch to add.
:param current_commit_count: Number of commits that has so far been added to the default branch.
:param branch_distance: Intended distance from the final default branch (which will have 8 commits) for the
commit to branch off (i.e. the branch will start at `default_branch~branch_distance`).
:param added: If the branch was previously added.
:returns: Whether the branch was (previously) added.
"""
if already_added:
return True
current_distance = branch_distance - (TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS - current_commit_count)
if current_distance < 0:
return False
create_branch(origin, name, commit=f"{default_branch()}~{current_distance}")
return True
bundles = [Path("bundle1.bundle"), Path("bundle2.bundle")]
previous_bundle = Path("previous.bundle")
target = create_repo("target", bare=True)
origin = create_repo("origin")
# Add the first commits and the branches that end up there. Add one additional commit to make sure the incremental
# bundle can't verify against an empty repo.
half_of_total_commits = TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS // 2
add_commits(origin, count=1 + half_of_total_commits)
b1 = add_branch("b1", half_of_total_commits, distance1, already_added=False)
b2 = add_branch("b2", half_of_total_commits, distance1 + distance2, already_added=False)
b3 = add_branch("b3", half_of_total_commits, distance1 + distance2 + distance3, already_added=False)
backup_bundle_main("create", origin, bundles[0], "--previous-bundle-location", previous_bundle)
# Add the last commits and the rest of the branches
add_commits(origin, count=half_of_total_commits)
b1 = add_branch("b1", TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS, distance1, already_added=b1)
b2 = add_branch("b2", TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS, distance1 + distance2, already_added=b2)
b3 = add_branch("b3", TOTAL_COMMITS_FOR_INCLUSIONS_EXCLUSIONS, distance1 + distance2 + distance3, already_added=b3)
# Each branch should now have been added
assert b1
assert b2
assert b3
backup_bundle_main("create", origin, bundles[1], "--previous-bundle-location", previous_bundle)
# The incremental backup contains all references, and is not a full backup
assert set(list_references_in_repo(origin)) == set(list_references_in_repo(bundles[1]))
assert not bundle_verifies(target, bundles[1])
backup_bundle_main("restore", target, bundles[0])
backup_bundle_main("restore", target, bundles[1], "--force")
# Restoring the backups succeeded
assert_repos_equal(origin, target)
@pytest.mark.parametrize(
"commit",
[
# Lambdas, because default_branch() only becomes available later on
default_branch,
lambda: f"{default_branch()}~1",
lambda: f"{default_branch()}~2",
lambda: f"{default_branch()}~3",
],
)
def test_create_new_tag_in_incremental_backup(commit: Callable[[], str]) -> None:
"""
Verify that a new tag shows up in an incremental backup.
:param commit: The commit to create the tag on.
"""
bundles = [Path("bundle1.bundle"), Path("bundle2.bundle")]
previous_bundle = Path("previous.bundle")
metadata = Path("metadata.json")
origin = create_repo("origin")
add_commits(origin, count=2)
target = create_repo("target", bare=True)
backup_bundle_main(
"create", origin, bundles[0], "--previous-bundle-location", previous_bundle, "--metadata", metadata
)
# Add a few commits and the new tag
add_commits(origin, count=2)
create_tag(origin, "tagged", commit=commit())
# Create the incremental backup
backup_bundle_main(
"create", origin, bundles[1], "--previous-bundle-location", previous_bundle, "--metadata", metadata
)
backup_bundle_main("restore", target, bundles[0])
backup_bundle_main("restore", target, bundles[1], "--force")
# Restoring the backups succeeded
assert_repos_equal(origin, target)
def test_create_requires_actual_git_repo() -> None:
"""
Verify that attempting to create a backup from something that is not a git repo fails.
"""
origin = Path("origin")
origin.mkdir()
(origin / "some_file").write_text("bla")
with pytest.raises(GitCallFailedError):
backup_bundle_main("create", origin, "bundle.bundle")
def test_create_from_empty_directory_requires_remote() -> None:
"""
Verify that attempting to create a backup from an empty directory without specifying a remote fails.
"""
origin = Path("origin")
origin.mkdir()
with pytest.raises(MissingRemoteError):
backup_bundle_main("create", origin, "bundle.bundle")
def test_create_from_empty_directory() -> None:
"""
Verify that attempting to create a backup from an empty directory works.
"""
bundle = Path("bundle.bundle")
target = Path("target")
source = create_repo("source")
add_commits(source)
origin = Path("origin")
origin.mkdir()
backup_bundle_main("create", origin, bundle, "--remote", source)
# Creating the backup has caused a normal clone in the origin repo
assert_repos_equal(source, origin)
assert not is_bare_repo(origin)
backup_bundle_main("restore", target, bundle)
# Restoring the backups succeeded
assert_repos_equal(source, target)
def test_create_from_non_existent_directory() -> None:
"""
Verify that attempting to create a backup from a directory that does not exist still works.
"""
bundle = Path("bundle.bundle")
target = Path("target")
source = create_repo("source")
add_commits(source)
origin = Path("origin")
backup_bundle_main("create", origin, bundle, "--remote", source)
# Creating the backup has caused a normal clone in the origin repo
assert_repos_equal(source, origin)
assert not is_bare_repo(origin)
backup_bundle_main("restore", target, bundle)
# Restoring the backups succeeded
assert_repos_equal(source, target)
def test_create_from_empty_directory_mirror_mode() -> None:
"""
Verify that creating a backup from a non-existing directories works in mirror mode.
Also verifies that backing up from a bare repository works.
"""
origin = Path("origin")
bundle = Path("bundle.bundle")
target = Path("target")
source = create_repo("source")
add_commits(source)
backup_bundle_main("create", origin, bundle, "--remote", source, "--mirror")
# Creating the backup has caused a mirrored clone in the origin repo
assert_repos_equal(source, origin)
assert is_bare_repo(origin)
backup_bundle_main("restore", target, bundle)
# Restoring the backups succeeded
assert_repos_equal(source, target)
def test_create_in_mirror_mode_triggers_update_first() -> None:
"""
Verify that creating backups in mirror mode first triggers an update.
"""
bundles = [Path("bundle1.bundle"), Path("bundle2.bundle")]
previous_bundle = Path("previous.bundle")
source = create_repo("source")
add_commits(source)
origin = create_repo("origin", clone=source, mirror=True)
target = create_repo("target", bare=True)
# Add some more commits to the source and create a full backup of origin
add_commits(source)
backup_bundle_main("create", origin, bundles[0], "--previous-bundle-location", previous_bundle, "--mirror")
backup_bundle_main("restore", target, bundles[0])
# Restoring will show the new commits to source to have been included
assert_repos_equal(source, target)
# Add some more commits to the source and create an incremental backup
add_commits(source)
backup_bundle_main("create", origin, bundles[1], "--previous-bundle-location", previous_bundle, "--mirror")
backup_bundle_main("restore", target, bundles[1], "--force")
# Restoring will show the new commits to source to have been included
assert_repos_equal(source, target)
@pytest.mark.parametrize(
"create",
[
False,
True,
],
)
def test_create_to_timestamped_bundle(*, create: bool) -> None:
"""
Verify that creating timestamped backups works.
:param create: Create files to make sure the non-timestamped bundle can't be written.
"""
bundle_dir = Path("bundle_dir")
bundle = bundle_dir / "bundle.bundle"
previous_bundle = Path("previous.bundle")
origin = create_repo("origin")
add_commits(origin)
target = create_repo("target", bare=True)
if create:
# Make it "impossible" to try and write the original file.
# This verifies that it's not a write-then-move implementation.
bundle.mkdir(parents=True)
(bundle / "some_file").write_text("bla")
backup_bundle_main("create", origin, bundle, "--previous-bundle-location", previous_bundle, "--timestamp")
# Bundle file should not have been written
if create:
assert bundle.exists()
assert not bundle.is_file()
else:
assert not bundle.exists()
# Exactly one file was written
assert len([found_bundle for found_bundle in bundle_dir.iterdir() if found_bundle.is_file()]) == 1
# Bundle files have the timestamp injected as the second-to-last suffix
assert all(
Path(found_bundle.stem).stem == bundle.stem and found_bundle.suffix == bundle.suffix
for found_bundle in bundle_dir.iterdir()
if found_bundle.is_file()